Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime number generator in Python [duplicate]

I'm trying to write a program to display prime numbers in the interval from 2 to 50.

def primeNr(interval):
    print("Prime numbers from 2 to ",interval,"/n")

    for i in range(1, interval):
        c=0
        for j in range(1, i):
            if(i%j==0):
                c+=1
        if(c==2):
            print (i)

but I'm getting the wrong output (4, 9, 25, 49) when I call it (primeNr(50)) - I have no idea why.

As an extra question - How can I make the following code return a list with the following numbers, and then let's say I want to have two variables p and q which pick a random number from the prime numbers list, like

p=primeNr(50)
q=primeNr(50)

(Yes, it's linked to RSA).

like image 411
bashbin Avatar asked Jan 23 '26 09:01

bashbin


1 Answers

The second parameter to range is not inclusive, so you need to do the following: (you can check out the document here: definition of python range)

for j in range(1, i + 1)

There are some opportunities for improvement mathematically, for example, you only need to loop up to math.sqrt, and the first moment you realize a number is not a prime, just break. (still not most optimized, to further optimize, you can check out various prime sieves).

import math

def primeNr(interval):
    print("Prime numbers from 2 to ", interval)

    #if interval itself should be included, then change this to range(2, interval + 1)
    for i in range(2, interval):
        isPrime = True
        for j in range(2, int(math.sqrt(i)) + 1):
            if i % j == 0:
                isPrime = False
                break
        if isPrime:
            print(i)

primeNr(50)

Below is based on some suggested edit made by @aryamccarthy (thanks for pitching the idea!). It utilizes a particular python syntax - for...else (The else clause executes when the loop completes normally without encountering any break):

import math

def primeNr(interval):
    print("Prime numbers from 2 to ", interval)

    for i in range(2, interval + 1):
        for j in range(2, int(math.sqrt(i)) + 1):
            if i % j == 0:
                break
        else:
            print(i)

primeNr(50)
like image 120
Peter Pei Guo Avatar answered Jan 25 '26 21:01

Peter Pei Guo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!