
Problem
Solution
Submissions
Sum of the Series 1² + 2² + ... + n²
Certification: Basic Level
Accuracy: 44.44%
Submissions: 9
Points: 5
Write a C++ program to calculate the sum of the series 1² + 2² + 3² + ... + n², where n is a positive integer.
Example 1
- Input: n = 5
- Output: 55
- Explanation:
- Step 1: Calculate the sum of squares from 1 to 5: 1² + 2² + 3² + 4² + 5².
- Step 2: 1² = 1, 2² = 4, 3² = 9, 4² = 16, 5² = 25.
- Step 3: Sum = 1 + 4 + 9 + 16 + 25 = 55.
- Step 4: Alternatively, use the formula: sum = n(n+1)(2n+1)/6 = 5(5+1)(2×5+1)/6 = 5×6×11/6 = 55.
Example 2
- Input: n = 10
- Output: 385
- Explanation:
- Step 1: Calculate the sum of squares from 1 to 10: 1² + 2² + 3² + ... + 10².
- Step 2: 1² = 1, 2² = 4, ..., 10² = 100.
- Step 3: Sum = 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100 = 385.
- Step 4: Alternatively, use the formula: sum = n(n+1)(2n+1)/6 = 10(10+1)(2×10+1)/6 = 10×11×21/6 = 385.
Constraints
- 1 ≤ n ≤ 10^4
- Time Complexity: O(1) or O(n)
- 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 mathematical formula for the sum of squares: n(n+1)(2n+1)/6.
- Alternatively, you can iterate through each number and add its square to the sum.
- Be careful about integer overflow for larger values of n.
- For large values of n, consider using a long long int data type.