Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime Numbers python

Tags:

python

I'm a beginning programmer in python and have a question about my code I'm writing:

number = int(input("Enter a random number: "))

for num in range(1, number + 1) :
    for i in range(2, num) :
         if (num % i) == 0 :
            break
         else :
             print(num)
             break

When I run this program I also get 9, 15 21 as output. But these are not prime numbers. What is wrong with my code?

Thanks!

like image 398
bvdabjorn Avatar asked Oct 30 '22 09:10

bvdabjorn


1 Answers

With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.

You can use something like this:

number = int(input("Enter a random number: "))

for num in range(1, number + 1):
    prime = True
    for i in range(2, num):
        if (num % i) == 0:
            prime = False
            break
    if prime:
        print(num)

It sets prime to False when it encounters a divisor without rest.

like image 92
arx5 Avatar answered Nov 15 '22 16:11

arx5