Tutorialspoint
Problem
Solution
Submissions

Find the Sum of Natural Numbers up to N

Certification: Basic Level Accuracy: 85.71% Submissions: 42 Points: 5

Write a Python program that calculates the sum of the first N natural numbers.

Example 1
  • Input: N = 10
  • Output: 55
  • Explanation:
    • Step 1: We need to find the sum of numbers from 1 to 10.
    • Step 2: Use the formula sum = N * (N + 1) / 2 for the sum of first N natural numbers.
    • Step 3: sum = 10 * (10 + 1) / 2 = 10 * 11 / 2 = 110 / 2 = 55
    • Step 4: Return the sum: 55
Example 2
  • Input: N = 100
  • Output: 5050
  • Explanation:
    • Step 1: We need to find the sum of numbers from 1 to 100.
    • Step 2: Use the formula sum = N * (N + 1) / 2 for the sum of first N natural numbers.
    • Step 3: sum = 100 * (100 + 1) / 2 = 100 * 101 / 2 = 10100 / 2 = 5050
    • Step 4: Return the sum: 5050
Constraints
  • 1 ≤ N ≤ 10^9
  • Time Complexity: O(1) when using the mathematical formula
  • Space Complexity: O(1)
NumberFunctions / MethodsHCL TechnologiesDropbox
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 formula: sum = N * (N + 1) / 2

The following are the steps to find the sum of natural numbers up to N:

 
  • Define the function sum_of_natural_numbers(n).
  • Use the formula sum = n * (n + 1) // 2.
  • Return the calculated sum.
  • Call the function and print the result.

Submitted Code :