Sum Of Squares Of First N Natural Numbers

Easy
0/40
Average time to solve is 15m
profile
Contributed by
7 upvotes
Asked in companies
SamsungSprinklrIncture Technologies

Problem statement

You are given an integer 'N'. You need to find the sum of squares of the first 'N' natural numbers.

For example:
If 'N' = 4. You need to return 1^2 + 2^2 + 3^2 + 4^2 = 30.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains a single integer 'T', representing the number of test cases or queries to be run. 
The first and the only line of each test case contains an integer 'N'.
Output Format:
For each test case, return the sum of squares of the first 'N' natural numbers in a single line.
Constraints:
1 ≤ T ≤ 10^4
1 ≤ N ≤ 5*10^5

where 'T' is the number of test cases and 'N' is the given number.
Time Limit: 1 sec.

Note:

You are not required to print the expected output, it has already been taken care of. Just implement the function.
Sample Input 1:
3
4
1
6
Sample Output 1:
30
1
91
Explanation of Input 1:
The first test case has already been explained in the problem statement.
For the second test case, 'N' = 1. So the sum would be =  1^2 = 1.
For the third test case, 'N' = 6. So the sum would be =  1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 = 91.
Sample Input 2:
3
12
2
9
Sample Output 2
650
6
285
Hint

Sum the squares of first ‘N’ natural numbers.

Approaches (3)
Brute Force - Recursive
  • Write a recursive solution for adding the sum of the squares of the first ‘N’ natural numbers.
  • The base case would be the sum of the first natural number, which is 1.
  • Sum up the squares of each number from 1 to ‘N’.
  • Finally, return this sum.
Time Complexity

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

Since we are traversing from 1 to ‘N’.

Space Complexity

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

Considering the recursive stack space.

Code Solution
(100% EXP penalty)
Sum Of Squares Of First N Natural Numbers
Full screen
Console