Tutorialspoint
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)
NumberVariables and Data TypesTech MahindraDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Define a function sumOfSquareSeries that takes an integer n.

 Step 2: Apply the mathematical formula: n(n+1)(2n+1)/6 to calculate the sum directly.
 Step 3: Return the calculated sum.
 Step 4: (Alternative approach) Initialize a sum variable to 0.
 Step 5: (Alternative approach) Use a for loop from i=1 to i=n.
 Step 6: (Alternative approach) For each iteration, add i^2 to the sum.
 Step 7: (Alternative approach) Return the final sum.

Submitted Code :