Given two numbers find the sum of prime numbers between them both inclusive in Python

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.

2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6.

Source Code

# Python program to display all the prime numbers within an interval lower = 900 upper = 1000 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)

Output

Prime numbers between 900 and 1000 are: 907 911 919 929 937 941 947 953 967 971 977 983 991 997

Here, we store the interval as lower for lower interval and upper for upper interval, and find prime numbers in that range. Visit this page to learn how to check whether a number is prime or not.

Here's my version, which I kept as close as possible to the original, while fixing some errors and making some adjustments.

def isPrime(n, i=2): # since you always use 2, just make it default if i == n-1: return True # return a boolean True instead of a string elif n%i == 0: return False # return a boolean False instead of a string else: return isPrime(n, i+1) def sumOfPrime(m,n,total=0): # we will need to carry the total around, make default to 0 if 0 < m <= n: # we can simplify this complex condition if isPrime(m): total += m # if it's prime, increase the total... return sumOfPrime(m+1, n, total) # and pass it to the next recursion return total # if this is the last recursion, return total # Example run total = sumOfPrime(10,45) print(total) # prints 264

In this article, we will discuss the concept of Python program to calculate sum of prime numbers between 1 to n

In this code, we are going to learn how to find sum of prime numbers 1 to n using different methods in Python language.

This is done using for loop, in Python language

Code to display sum of prime numbers

Code to calculate sum of prime numbers using for loop

In this program, we will calculate sum of prime numbers 1 to n using for loop in Python language

Program 1

#takes input from the user max=int(input("Enter the maximum value for find sum of primes:")) sum=0 for num in range(2,max+1): i=2 for i in range(2,num): if(int(num%i==0)): i=num break; #when the number is prime calculate sum if i is not num: sum+=num print("Sum of all prime numbers 1 to ",max,":",sum)

When the above code is executed, it produces the following result

Enter the maximum value for find sum of primes:100 Sum of all prime numbers 1 to  100 :1058

Code to calculate sum of prime numbers between 1 to n -method 2

Program 2

#Python program to find sum of prime numbers from 1 to n maximum=int(input("Please enter the maximum value: ")) total=0 for Number in range(1,maximum+1): count=0; for i in range(2,(Number//2+1)): if(Number%i==0): count=count+1 break if(count==0 and Number !=1): total=total+Number print("Sum of prime numbers from 1 to %d=%d"%(maximum,total))

When the above code is executed, it produces the following result

Please enter the maximum value: 50
Sum of prime numbers from 1 to 50=328

Code to calculate sum of prime numbers between 1 to n -method 3

Program 3

#Python program to find sum of prime numbers from 1 to n maximum=int(input("Please enter the maximum value: ")) total=0 for Number in range(1,maximum+1): count=0; for i in range(2,(Number//2+1)): if(Number%i==0): count=count+1 break if(count==0 and Number !=1): # print("%d"%Number) total=total+Number print("Sum of prime numbers from 1 to %d=%d"%(maximum,total))

When the above code is executed, it produces the following result

Please enter the maximum value: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Sum of prime numbers from 1 to 100=1060

# Take input from user upto = int(input("Find sum of prime numbers upto : ")) sum = 0 for num in range(2, upto + 1): i = 2 for i in range(2, num): if (int(num % i) == 0): i = num break; #If the number is prime then add it. if i is not num: sum += num print("\nSum of all prime numbers upto", upto, ":", sum)

Given an even number (greater than 2 ), print two prime numbers whose sum will be equal to given number. There may be several combinations possible. Print only first such pair. 
An interesting point is, a solution always exist according to Goldbach’s conjecture.
Examples : 
 

Input: n = 74 Output: 3 71 Input : n = 1024 Output: 3 1021 Input: n = 66 Output: 5 61 Input: n = 9990 Output: 17 9973

The idea is to find all the primes less than or equal to the given number N using Sieve of Eratosthenes. Once we have an array that tells all primes, we can traverse through this array to find pair with given sum. 
 

bool SieveOfEratosthenes(int n, bool isPrime[])

    isPrime[0] = isPrime[1] = false;

    for (int i = 2; i <= n; i++)

    for (int p = 2; p * p <= n; p++) {

        if (isPrime[p] == true) {

            for (int i = p * p; i <= n; i += p)

void findPrimePair(int n)

    SieveOfEratosthenes(n, isPrime);

    for (int i = 0; i < n; i++) {

        if (isPrime[i] && isPrime[n - i]) {

            cout << i << " " << (n - i);

bool SieveOfEratosthenes(int n, bool isPrime[])

    isPrime[0] = isPrime[1] = false;

    for (int i = 2; i <= n; i++)

    for (int p = 2; p * p <= n; p++) {

        if (isPrime[p] == true) {

            for (int i = p * p; i <= n; i += p)

void findPrimePair(int n)

    SieveOfEratosthenes(n, isPrime);

    for (int i = 0; i < n; i++) {

        if (isPrime[i] && isPrime[n - i]) {

    static boolean SieveOfEratosthenes(int n, boolean isPrime[])

        isPrime[0] = isPrime[1] = false;

        for (int i = 2; i <= n; i++)

        for (int p = 2; p * p <= n; p++) {

            if (isPrime[p] == true) {

                for (int i = p * p; i <= n; i += p)

    static void findPrimePair(int n)

        boolean isPrime[] = new boolean[n + 1];

        SieveOfEratosthenes(n, isPrime);

        for (int i = 0; i < n; i++) {

            if (isPrime[i] && isPrime[n - i]) {

                System.out.print(i + " " + (n - i));

    public static void main(String[] args)

def SieveOfEratosthenes(n, isPrime):

    isPrime[0] = isPrime[1] = False

    SieveOfEratosthenes(n, isPrime)

        if (isPrime[i] and isPrime[n - i]):

    static bool SieveOfEratosthenes(int n, bool []isPrime)

        isPrime[0] = isPrime[1] = false;

        for (int i = 2; i <= n; i++)

        for (int p = 2; p * p <= n; p++)

                for (int i = p * p; i <= n; i += p)

    static void findPrimePair(int n)

        bool []isPrime=new bool[n + 1];

        SieveOfEratosthenes(n, isPrime);

        for (int i = 0; i < n; i++)

            if (isPrime[i] && isPrime[n - i])

                Console.Write(i + " " + (n - i));

    public static void Main ()

function SieveOfEratosthenes($n, &$isPrime)

    $isPrime[0] = $isPrime[1] = false;

    for ($i = 2; $i <= $n; $i++)

    for ($p = 2; $p * $p <= $n; $p++)

        if ($isPrime[$p] == true)

function findPrimePair($n)

    $isPrime = array_fill(0, $n + 1, NULL);

    SieveOfEratosthenes($n, $isPrime);

    for ($i = 0; $i < $n; $i++)

            echo $i . " " . ($n - $i);

    function SieveOfEratosthenes(n,isPrime)

        isPrime[0] = isPrime[1] = false;

        for (let i = 2; i <= n; i++)

        for (let p = 2; p * p <= n; p++)

                for (let i = p * p; i <= n; i += p)

    function findPrimePair(n)

        let isPrime = new Array(n+1);

        SieveOfEratosthenes(n, isPrime);

        for (let i = 0; i < n; i++)

            if (isPrime[i] && isPrime[n - i])

                document.write(i + " " + (n - i));

Output: 
 

3 71

Time complexity: O(n*log(logn))

Auxiliary Space: O(n)

This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Article Tags :