Tutorialspoint
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)
NumberVariables and Data TypesPwCSwiggy
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 formula: n(n + 1)(2n + 1) / 6
  • Handle edge case n = 1 explicitly
  • Ensure calculations use sufficient data types to prevent overflow

Steps to solve by this approach:

 Step 1: Apply the mathematical formula for sum of squares: n(n+1)(2n+1)/6.

 Step 2: Calculate each component of the formula: n, (n+1), and (2n+1).
 Step 3: Multiply these three values together.
 Step 4: Divide the product by 6 to get the final result.
 Step 5: Return the calculated sum of squares.

Submitted Code :