
Problem
Solution
Submissions
Sum of the Squares of Natural Numbers
Certification: Basic Level
Accuracy: 100%
Submissions: 3
Points: 5
Write a C++ program to calculate the sum of squares of the first 'n' natural numbers.
Example 1
- Input: n = 3
- Output: 14
- Explanation:
- Step 1: Identify the first n natural numbers: 1, 2, 3
- Step 2: Calculate the square of each number: 1^2 = 1, 2^2 = 4, 3^2 = 9
- Step 3: Sum the squares: 1 + 4 + 9 = 14
- Step 4: Return the sum: 14
Example 2
- Input: n = 5
- Output: 55
- Explanation:
- Step 1: Identify the first n natural numbers: 1, 2, 3, 4, 5
- Step 2: Calculate the square of each number: 1^2 = 1, 2^2 = 4, 3^2 = 9, 4^2 = 16, 5^2 = 25
- Step 3: Sum the squares: 1 + 4 + 9 + 16 + 25 = 55
- Step 4: Return the sum: 55
Constraints
- 1 ≤ n ≤ 10^6
- Note: You can use the mathematical formula: sum of squares of first n natural numbers = n(n+1)(2n+1)/6
- Time Complexity: O(1) when using the formula
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the formula: n(n + 1)(2n + 1) / 6
- Handle edge case n = 1 explicitly
- Ensure calculations use sufficient data types to prevent overflow