0

This program is for listing all the prime numbers between 1 and 1000, but my teacher would like me to include 1 in the results.

I tried to change it to say if num >= 1: and for i in range(1,num), but then when I ran it, the only result was 1 is a prime number!. Thanks!

for num in range(1,1001):
   if num > 1:
       for i in range(2,num):
           if (num % i) == 0:
               break
       else:
           print(num,"is a prime number!")
Avi Turner
  • 9,682
  • 7
  • 47
  • 70
user6627144
  • 25
  • 1
  • 6
  • 3
    First thing would be, `if num >= 1:` after that, you have `if (num % i) == 0 break` that is why it is stopping there. – Evan Carslake Jul 27 '16 at 02:49
  • 1
    Weird. When I run this, I get the expected output. – intboolstring Jul 27 '16 at 02:52
  • 1
    I'm also getting the expected result. – shiva Jul 27 '16 at 02:55
  • After you explain to your teacher what @StefanPochmann has mentioned, you may as well just `print(1,"is a prime number!")` at the beginning of your script. – barak manos Jul 27 '16 at 06:17
  • As a sidenote, I would recommend you to look at the Sieve of Eratosthenes algorithm to find prime numbers, since it's a much more efficient solution: http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python – Mumpo Jul 27 '16 at 08:00

3 Answers3

1

You should not write for i in range(1, num):, because (any number) % 1 == 0. if num >= 1: can also be removed, because it's always true.

Try the following code:

for num in range(1, 1001):
    for i in range(2, num):
        if num % i == 0:
            break
    else:
        print num, 'is a prime number'

And remember, technically speaking, 1 isn't a prime number.

nalzok
  • 13,395
  • 18
  • 64
  • 118
0

Leave your code as is and above the main for loop add:

print("1 is a prime number")
Nick stands with Ukraine
  • 6,365
  • 19
  • 41
  • 49
0
a = int(input("enter the start number"))
b = int(input("enter the end number"))
for i in range(a,b+1):
    if i > 1:
        for j in range(2,i):
            if i % j == 0:
                break
        else:
            print(i,"is a prime number")