简体   繁体   中英

Prime number generator in Python

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

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)

range does not include its end limit. Thus you are finding numbers with three divisors (which are the squares of primes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM