Simple Python program to find the sum of prime numbers between two given digits

In this post I will explain you how to find if a number is prime or not and then add the prime numbers between two given numbers.

First of all let us check if a number is prime or not:

def checkPrime(n):
     flag = 0
     for j in range(2,n):
         #print(n,j)
         if(n%j == 0):
             flag = 1
     #print(flag)
     if(flag == 1):
         return 0
     else:
         return n

As you can see this subroutine does the job of checking if a number is prime or not. If we are good at Math then this logic is pretty simple. But still let me explain, a prime number is the one that is divisible by 1 and itself. So simply we need to find a number when divided by any number lower than it gives a reminder equal to zero which means it is divisble by that number.

In our subroutine the part if(n%j ==0) does the same. And now the remaining portion of adding all the prime numbers between two given numbers.

#program to find sum of primes between two given numbers
 def checkPrime(n):
     flag = 0
     for j in range(2,n):
         #print(n,j)
         if(n%j == 0):
             flag = 1
     #print(flag)
     if(flag == 1):
         return 0
     else:
         return n
 #execution starts from here
 a = int(input("Enter first number: "))
 b = int(input("Enter second number: "))
 total = 0 #variable to store sum of primes
 for i in range(a,b):
     res = checkPrime(i)
     total += res
 print(total)

In the rest of the program we take user input and check the primes between those numbers and add them up to get result.

If you have any doubts don’t forget to comment.

Leave a Reply

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