|
U
Pro14. Count Nested Loop Iterations
Easy
Problem Description
Consider the following nested loop structure:
long long count = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= i; j++) {
count++;
}
}Given a non-negative integer N, calculate the exact final value of count. Notice that the total number of inner loop executions is the arithmetic series:
count=i=1∑Ni=2N(N+1)
Input Format
A single line containing an integer N (0≤N≤106).
Output Format
Print the total number of iterations as a 64-bit integer.
Example 1:
Input:
4
Output:
10
Explanation: Inner loop runs 1 + 2 + 3 + 4 = 10 times.
Example 2:
Input:
0
Output:
0
Explanation: When N = 0, the outer loop never executes.
Example 3:
Input:
1
Output:
1
Explanation: When N = 1, exactly 1 iteration occurs.
Constraints:
0 <= N <= 10^6Time complexity target: O(1)Auxiliary space target: O(1)
Follow up:What would be the closed-form iteration count if the inner loop condition was j <= i * i?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
input =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit