U

14. 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 NN, calculate the exact final value of count. Notice that the total number of inner loop executions is the arithmetic series:

count=∑i=1Ni=N(N+1)2\text{count} = \sum_{i=1}^{N} i = \frac{N(N + 1)}{2}

Input Format

A single line containing an integer NN (0≤N≤1060 \le N \le 10^6).

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^6
  • Time 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