top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Sum of N Natural Numbers

Introduction

In computer programming, Python is an extremely versatile language. It is known for its simplicity and readability among programmers. It has a vast landscape of mathematical computations and in this, the sum of N natural numbers emerges as a classic problem. 

In this case, Python offers elegant solutions to deal with it. It devises a program that calculates the sum of the first N natural numbers by using its syntax. 

In this tutorial, let's learn in detail the program to find the sum of N natural numbers, the sum of N natural numbers formula, the sum of N numbers in Python using recursion, and many more. 

Overview 

Calculating the sum of N natural numbers is straightforward with Python programming. These natural numbers are generally positive integers starting from 1, and their sum could be concluded in various methods. The three primary approaches to concluding the sum of N natural numbers are: 

  • Loop: It is one of the basic methods to iterate through the numbers and add them from 1 to N. It is a simple and efficient method for calculating the small values of N. 

  • Formula: To calculate the larger values of N, a direct formula is available that calculates the first N natural numbers. It is a complex method and only suited for large values and performance-critical applications. 

  • Recursion: This technique computes the sum of N natural numbers into smaller subproblems and recursively finds the sum reaching its natural base case. It might not be as efficient as loop or the original formula, but it illustrates the power of recursion in problem-solving. 

Sum of N Natural Numbers in Python Using Recursion

Code:

##sum of n Natural Numbers in Python
x=int(input("Enter the number "))
def sum(x):
    ##Handling the Base Case
    if(x==1):
        return 1
    else:
        return x+sum(x-1)   
##Calling the Method sum() to Calculate the Sum
result=sum(x)
print(result)          

Explanation:

  • The program prompts the user to enter a number using int(input("Enter the number ")). The input is stored in the variable x.

  • The program defines a function named sum(x) that takes an integer parameter x, which represents the number up to which the sum of natural numbers needs to be calculated.

  • Inside the sum function:

It checks for the base case: if (x == 1). When x is equal to 1, the function returns 1, as the sum of the first natural number (1) is 1.

If x is not equal to 1 (i.e., it's greater than 1), the function uses recursion to calculate the sum of the first x natural numbers. It does this by returning x + sum(x - 1). This recursive call calculates the sum of the first x-1 natural numbers and then adds x to it.

  • After defining the sum function, the program calls it with the user-input value x, and the result is stored in the variable result.

  • Finally, the program prints the result, which is the sum of the first n natural numbers, calculated using recursion.

For example, if you input 5, the program will calculate the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5), which is 15, and print it to the console.

Sum of N Natural Numbers in Python Using Loop 

Code:

##Sum of n Natural Numbers in Python
p=int(input("Enter the number "))
s=0
##Itearting on the range of natural number
for a in range(1,p+1,1):
    s+=a
print(s)

Explanation:

  • The program prompts the user to enter a number using int(input("Enter the number ")). The input is stored in the variable p.

  • The program initializes an integer variable s to 0. This variable will be used to store the sum of the natural numbers.

  • The program uses a for loop to iterate over the range of natural numbers from 1 to p+1. The range() function generates a sequence of numbers from 1 to p (inclusive) with a step of 1. For each value of a in the range, the loop performs the following operation:

s += a: The current value of a is added to the variable s. This accumulates the sum of natural numbers as the loop iterates.

  • After the loop completes, the program will finish calculating the sum of the first p natural numbers, which is stored in the variable s.

  • Finally, the program prints the result, which is the sum of the first n natural numbers.

For example, if you input 5, the program will calculate the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5), which is 15, and print it to the console.

Sum of N Natural Numbers Formula 

The sum of the first N natural numbers is a mathematical concept that calculates the total sum of all positive integers starting from 1 up to the given positive integer N. It is often denoted by the Greek letter sigma (Σ) and represented as follows:

Σ = 1 + 2 + 3 + 4 + 5 + ... + N

For example, if N = 5, then the sum of the first 5 natural numbers would be:

Σ = 1 + 2 + 3 + 4 + 5 = 15

The formula for finding the sum of the first N natural numbers is derived from a pattern noticed by mathematicians. It can be calculated using the following formula:

Sum = N * (N + 1) / 2

Let's break down this formula to understand how it works:

  • N: This is the given positive integer up to which you want to find the sum of natural numbers.

  • (N + 1): Adding 1 to N is used in the formula because we are calculating the sum up to N (inclusive). So, if N is 5, we need to include the number 5 in the sum.

  • N * (N + 1): This part of the formula calculates the product of N and (N + 1).

  • N * (N + 1) / 2: The division by 2 is done to account for the double counting that occurs when finding the sum of consecutive numbers. Since each number appears twice (e.g., 1 + 2 = 3 and 2 + 1 = 3), dividing by 2 eliminates the double counting, giving us the correct sum.

For example, using the formula for N = 5:

Sum = 5 * (5 + 1) / 2 = 5 * 6 / 2 = 30 / 2 = 15

And as you can see, this matches the sum we calculated directly earlier (1 + 2 + 3 + 4 + 5 = 15).

This formula is quite handy when you need to find the sum of a large number of natural numbers quickly, as it saves you from adding them one by one manually.

Code:

##sum of n natural numbers in python
#Enter the number 
p=int(input("Enter the number "))
##Finding the sum of natural numbers upto n 
s=(p*(p+1))//2
print(s)

Explanation:

The program calculates the sum of the first n natural numbers using the formula sum = (n * (n + 1)) // 2. Let's go through the code step by step:

  • The program prompts the user to enter a number using int(input("Enter the number ")). The input is stored in the variable p.

  • The program calculates the sum of natural numbers using the formula:

          sum = (p * (p + 1)) // 2

Here's how this formula works:

  • p * (p + 1): Multiplies the given number p by its consecutive number p + 1.

  • // 2: Integer division by 2. This is done to divide the result of the multiplication by 2, effectively calculating the sum of the first p natural numbers.

  • The calculated sum of the first n natural numbers is stored in the variable s.

  • Finally, the program prints the result, which is the sum of the first n natural numbers.

For example, if you input 5, the program will calculate the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5), which is 15, and print it to the console. The program uses a direct formula to compute the sum efficiently, without the need for any loops or recursion.

Sum of n natural numbers in Python using function

Code:

def sum_of_natural_numbers(n):
    # Calculate the sum using the formula: Sum = n * (n + 1) / 2
    return n * (n + 1) // 2

# Get the value of n from the user
try:
    n = int(input("Enter a positive integer (n): "))
    if n <= 0:
        raise ValueError
    # Calculate and display the sum of the first n natural numbers
    result = sum_of_natural_numbers(n)
    print(f"The sum of the first {n} natural numbers is: {result}")
except ValueError:
    print("Invalid input! Please enter a positive integer.")

Explanation:

This is a Python program to find the sum of first n natural numbers using the formula Sum = n * (n + 1) / 2. Let's go through the code step by step:

  • The program defines a function named sum_of_natural_numbers(n), which takes an integer parameter n.

  • Inside the function:

The sum of the first n natural numbers is calculated using the formula Sum = n * (n + 1) // 2. The // operator is used for integer division, which ensures that the result is an integer.

uncheckedThe calculated sum is returned from the function.

  • The program then prompts the user to enter a positive integer n using int(input("Enter a positive integer (n): ")).

  • The program checks if the input value n is less than or equal to 0. If it is, the program raises a ValueError.

  • If the input value n is valid (greater than 0), the program proceeds to calculate and display the sum of the first n natural numbers using the sum_of_natural_numbers(n) function. The result is stored in the variable result.

  • Finally, the program prints the calculated sum along with a message to inform the user of the sum of the first n natural numbers.

The code also handles the case of invalid input by catching the ValueError and printing an error message.

When you run this Python program, it will prompt you to enter a positive integer n, calculate the sum of the first n natural numbers using the formula, and display the result on the console. If you enter an invalid input (e.g., a non-positive integer or a non-integer value), it will inform you of the error and ask for a valid input.

Sum of N Natural Numbers Using While Loop in Python 

Code:

def sum_of_natural_numbers(n):
    # Initialize variables
    sum = 0
    num = 1
    
    # Use a while loop to calculate the sum of the first n natural numbers
    while num <= n:
        sum += num
        num += 1

    return sum

# Get the value of n from the user
try:
    n = int(input("Enter a positive integer (n): "))
    if n <= 0:
        raise ValueError
    # Calculate and display the sum of the first n natural numbers
    result = sum_of_natural_numbers(n)
    print(f"The sum of the first {n} natural numbers is: {result}")
except ValueError:
    print("Invalid input! Please enter a positive integer.")

Conclusion 

In conclusion, calculating the sum of N natural numbers in Python is an essential component when it comes to programmers. There are distinct approaches to accomplish this task, but it is the task of the programmer to choose the most appropriate method based on N's value and other specific requirements for the said program. 

Understanding the trade-offs between the different approaches and choosing the most appropriate method is a key skill in programming that one should master. Even if one is dealing with basic arithmetic or sophisticated algorithms, Python's readability acts as a powerful ally for programmers. 

FAQs

  1. Who found the sum of N natural numbers? 

The mathematician Carl Friedrich Gauss is credited with developing the method for calculating the sum of the first N natural numbers integers. The legend has it that Gauss developed this formula as a young child in the early 19th century.

  1. How to define a function in Python? 

In Python, you can use the def keyword, function name, parentheses, and colon. The function body is indented under the def statement. 

  1. What are the 4 types of functions in Python? 

The four types of functions in Python are: 

  • Built-in functions. 

  • User-defined functions. 

  • Anonymous or Lambda functions. 

  • Recursive functions. 

Leave a Reply

Your email address will not be published. Required fields are marked *