Tutorial Playlist

187.Â # Sum of N Natural Numbers

Content

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.

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:

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.**Loop:**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.**Formula:**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.**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
function:**sum**

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.

**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.

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:

This is the given positive integer up to which you want to find the sum of natural numbers.**N:**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 + 1):**This part of the formula calculates the product of N and (N + 1).**N * (N + 1):**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.**N * (N + 1) / 2:**

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.

**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.

The 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.

**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.")

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.

**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.

**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.

**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.

PAVAN VADAPALLI

Popular

+91

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...