Python can be used for doing Mathematical Stuff specifically using Math Module, in this article I fill discuss How to find some of first n Natural Numbers using Python? Natural Numbers sequence start from 1 and goes up to positive infinity. So first 5 Natural Numbers will be 1, 2, 3, 4, 5 and first 10 Natural Numbers will be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Let’s for fininding sum of first 5 Natural Numbers, you need to do 1 + 2 + 3 + 4 + 5 but mathematically this summation can be sequezed in as n(n+1)/2 where n is number of Natural Numbers. Like for finding sum of first 5 natural numbers instead of doing 1 + 2 + 3 + 4 + 5, just do 5(5+1)/2 = 5(6)/2 = 15.
Quite Simple, so there can be two approaches for finding Sum of N Natural Numbers, let’s implement both of these and write Python Code for finding sum of n Natural Numbers.
1) Python Code for Finding Sum of N Natural Numbers
# Sum of natural numbers up to n num n = 10 # Checks if number is negative if n < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(n > 0): sum += n n -= 1 print("The sum is => ", sum)
The sum is => 55
Similarly, if you want to ask your user about How many Natural Numbers sum to find? then instead of having n = 10 on line 2 with n = input(‘Enter A Number’).
2) Short Way for Finding Sum of N Natural Numbers Using Python
# Sum of natural numbers up to n num user_input = input("Enter a Number => ") # Converting to int as input() by default is a string n = int(user_input) # Checks if number is negative if n < 0: print("Enter a positive number") else: sum = n * (n + 1)/2 print("The sum is => ", sum)
When running the above code, a prompt will be shown to user Enter a Number => after user enters number then code will be executed. If user entered non-negative then above code will show “Enter a positive number” otherwise code will execute and return sum of N Natural Numbers.