samedi 15 avril 2017

Python - Prime number generator

I did this function in C++ some years ago in reference to generating prime numbers:

void primeNr(int interval)
{
int i, j, c; // c for counter
cout << "Prime numbers from to 2 to " << interval << endl;

for (i = 1; i <= interval; i++) 
  {
    c = 0;
    for (j = 1; j <= i; j++)
        if (i % j == 0) // if the number i is divided by j, add 1 to counter
            c++;
    if (c == 2) // if a number has only two divisors => prime number
        cout << setw(3) << i;
  }
}

And when you call it in the main function: primeNr(50);, it will display prime numbers in the interval from 2 to 50.
Now, I'm new to python and I tried to translate the above code in python code:

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 wrong input (4, 9, 25, 49) when I call it (primeNr(50)) - I have no idea why.

As an extra question (not urgent) - How can I make the following code to 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)




Aucun commentaire:

Enregistrer un commentaire