
Given 'N' : 6
Sum of all even numbers till 'N' will be : 2 + 4 + 6 = 12
The first line of the input contains an integer 'T', denoting the number of test cases.
The first line and the only line of each test case contains an integer 'N'.
For each test case, print a single integer representing the sum of even numbers till 'N'.
Print a single 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^5
Time Limit: 1 sec
We can simply apply brute force and add numbers to a variable.
Here is the algorithm :
We can derive a formula to calculate the sum of even numbers till ‘N’.
Let the number given be : ‘N’. Then the even numbers need to be added will be {2, 4, 6,…., ‘N or ‘N - 1’}. Total even numbers from 1 to ’N' will be ‘N/2’. Example :
‘N’ : 4, even numbers till 4 : {2, 4}, count = ‘N/2’ = 2
‘N’ : 5, even numbers till 5 : {2, 4}, count = ‘N/2’ = 2
‘N’ : 1, even numbers till 1 : {}, count = ‘N/2’ = 0
The sequence of even numbers till ‘N’ forms an A.P. (arithmetic progression) with common difference, ‘D’ as 2, first element, ‘A’ as 2 and number of elements, ‘N’ as ‘N/2’ (as proved above).
Sum of A.P. is : (N/2) * (A + L) where ‘N’ is number of terms, ‘A’ is first number and ‘L’ is last number which can also be written as ‘A + (N - 1)D'.
Putting ‘N’ = ‘N/2’, ‘A’ = 2 and ‘D’ = 2 in above formula,
‘SUM' = (N/2*2) * (2 + 2 + (N/2 - 1)*2)
= (N/2) * (1 + 1 + N/2 - 1)
= (N/2) * (N/2 + 1)
We can calculate the sum using above formula directly.