If N = 3.
Sum of the first 3 natural numbers will be 1 + 2 + 3 = 6. Hence, the output will be 6.
The first line of the input contains an integer, 'T’, denoting the number of test cases.
The first line of each test case contains a single positive integer ‘N’.
For each test case, print the sum of first ‘N’ natural numbers.
Print a separate line for each test case.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6
Time limit: 1 sec
The idea of this approach is to go over each number from 1 to ‘N’ and add each number to the sum.
The sequence from 1 to ‘N’ is in Arithmetic progression(AP) with a common difference of 1.
We know that the sum of first ‘N’ terms of an arithmetic sequence is given by the following equation:
Sum = (n * (2 * a + (n - 1) * d)) / 2, here ‘a’ is the first term of AP , ‘d’ is the common difference and ‘n’ is the number of terms in the sequence.
In our case a = 1, d = 1 then Sum = n * (n + 1) / 2.
Hence, the sum of first ‘N’ natural numbers is N * (N + 1) / 2.
Here is the algorithm:
Return N * (N + 1) / 2.