Sum Of Even Numbers Till N

Easy
0/40
Average time to solve is 10m
profile
Contributed by
265 upvotes
Asked in companies
AmazonToluna India Pvt. Ltd.

Problem statement

You have been given a number 'N'. Your task is to find the sum of all even numbers from 1 to 'N' (both inclusive).

Example :

Given 'N' : 6
Sum of all even numbers till 'N' will be : 2 + 4 + 6 = 12
Detailed explanation ( Input/output format, Notes, Images )

Input Format :

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'.

Output Format :

For each test case, print a single integer representing the sum of even numbers till 'N'.

Print a single line for each test case.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.

Constraints :

1 <= T <= 10
1 <= N <= 10^5

Time Limit: 1 sec

Sample Input 1 :

2
6
2

Sample Output 1 :

12
2

Explanation For Sample Input 1 :

For test case 1 :
Sum of all even numbers till 6 will be : 2 + 4 + 6 = 12

For test case 2 :
Sum of all even numbers till 2 will be : 2

Sample Input 2 :

2
4
5

Sample Output 2 :

6
6

Explanation For Sample Input 2 :

For test case 1 :
Sum of all even numbers till 4 will be : 2 + 4 = 6

For test case 2 :
Sum of all even numbers till 5 will be : 2 + 4 = 6
Hint

Try to traverse till N.

Approaches (2)
Brute Force

We can simply apply brute force and add numbers to a variable.

 

Here is the algorithm :

 

  1. Create a variable (say, ‘SUM’) which will store the sum of even numbers and initialise it to 0.
  2. Create a variable (say, ‘i’ ) which we will use to iterate and initialise it to 2 (first even number).
  3. Run a loop till i is smaller then equal to ‘N’ and do :
    • Update ‘SUM’ to ‘SUM’ + ‘i’
    • Update ‘i’ to ‘i’ + 2 (We increment 2 times so that we can reach to next even number)
  4. Finally, return ‘SUM’
Time Complexity

O(N), where ‘N’ is the given integer.

 

We traverse till ‘N’ and iterate ‘N/2’ times to add numbers. Hence, the overall complexity will be O(N/2) i.e. O(N).

Space Complexity

O(1)

 

We use no extra space. Hence, the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Sum Of Even Numbers Till N
Full screen
Console