Sum Of Squares Of First N Natural Numbers
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.
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.
AnswerBot
1y
The task is to find the sum of squares of the first 'N' natural numbers.
Iterate from 1 to N and calculate the square of each number
Add all the squares together to get the final sum
Return the sum as th...read more
CodingNinjas
author
2y
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 s...read more
CodingNinjas
author
2y
Brute Force - Iterative
- Run a for loop from 1 to ‘N’.
- Sum up the squares of each number from 1 to ‘N’.
- Finally, return this sum.
O(1)
Since we are using constant extra sp...read more
CodingNinjas
author
2y
Mathematical Formula
- The sum of squares of first N natural numbers is given by: 1^2 + 2^2 + … N^2 = N*(N+1)*(2*N+1)/6
- This can be proved by mathematical induction.
- We can see that the formula is true for...read more
Add answer anonymously...
Top Paytm Business Analyst interview questions & answers
Popular interview questions of Business Analyst
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app