Tutorialspoint
Problem
Solution
Submissions

Sum of the First 'n' Natural Numbers

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a C++ program that calculates the sum of the first 'n' natural numbers.

Example 1
  • Input: n = 5
  • Output: 15
  • Explanation:
    • Step 1: Identify the first n natural numbers: 1, 2, 3, 4, 5.
    • Step 2: Calculate the sum: 1 + 2 + 3 + 4 + 5 = 15.
    • Step 3: Return the sum: 15.
Example 2
  • Input: n = 10
  • Output: 55
  • Explanation:
    • Step 1: Identify the first n natural numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
    • Step 2: Calculate the sum: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.
    • Step 3: Return the sum: 55.
Constraints
  • 1 ≤ n ≤ 10^6
  • Note: You can use the mathematical formula: sum of first n natural numbers = n(n+1)/2
  • Time Complexity: O(1) when using the formula
  • Space Complexity: O(1)
NumberControl StructuresWiproAirbnb
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) / 2
  • Handle edge case where n = 1 explicitly
  • Ensure calculations avoid integer overflow

Steps to solve by this approach:

 Step 1: Apply the mathematical formula: n(n+1)/2.

 Step 2: Calculate n+1.
 Step 3: Multiply n by the result from step 2.
 Step 4: Divide the product by 2.
 Step 5: Return the calculated sum.

Submitted Code :