Search code examples
python

Prime numbers using python


I've started learning python(python3) and I got this program for printing prime numbers This was my code:

a=int(input("Enter starting number"))
b=int(input("Enter the ending number"))
while(a!=b):
    for n in range(2, a-1):
        c=a%n
        if(c!=0):
            print(a)
            
        elif(c==0):
            break
    a+=1

I do realize the code is wrong for the finding out prime numbers as it will print some number like 9, 15, 21...which aren't prime numbers BUT HEAR ME OUT FIRST.

I ran the program and kept the values as a=4 b=7

I expected the output to be: 5 5 5 7 7 7 7 7

The answer I got was: 5 5

I can't understand the reason behind this output.

Can I get the explanation for the output?


Solution

  • The first issue is that in a loop, range(2,a-1) does not include the very last value. If you change it to range(2,a) you include the last value that you want to, and it does not include the value of a. That will then print 5 5 5. To get the 7's to show up, take a look at the logic of the While loop. The loop says, while a does not equal b, do what is in the loop. So, once a = b, the loop will no longer run. You want the loop to run until it equals b, run one last time, and then quit. So, you need to change it to, while a != b+1. This will get the output you expected. Here is the code changed.

    a=int(input("Enter starting number"))
    b=int(input("Enter the ending number"))
    while(a!=b+1):
        for n in range(2, a):
            c=a%n
            if(c!=0):
                print(a)
    
            elif(c==0):
                break
        a+=1