Radhu
Radhu

Reputation: 21

What's wrong with my program for prime number in a range?

To print the prime numbers in range program:

lower = int(input("Enter lower range: "))   
upper = int(input("Enter upper range: "))

for num in range(lower,upper + 1):

   # prime numbers are greater than 1

   if num > 1:

       for i in range(2,num):

           if (num % i) == 0:

               break
       else:
           print(num)

The output for the above is:

Enter lower range: 3
Enter upper range: 10

3
5
7

But,When I tried with the below code, the output is varying.

min=int(input("enter the min num"))

max=int(input("Enter the max num"))

for i in range(min,max+1):

    if i > 1:

        for j in range(2,i):

            if (i%j) == 0:

                break

            else:

                print(i)

Output:

enter the min num: 3
Enter the max num: 10

3
5
5
5
7
7
7
7
7
9

Upvotes: 0

Views: 95

Answers (3)

Nander Speerstra
Nander Speerstra

Reputation: 1526

You have an indentation difference:

for j in range(2,i):

        if (i%j) == 0:

            break

## This piece
        else:

            print(i)
## This piece

In your first example:

  • For each number, do a modulo calculation and break if it leads to 0
  • If none of the calculations lead to 0, you find a prime (and thus print it)

En your second example:

  • For each number, do a modulo calculation and break if it leads to 0
  • If it doesn't lead to 0: print the number. Which happens quite more often than the else in example 1.

Upvotes: 1

Obsidian
Obsidian

Reputation: 515

You;re printing the value after each check success. You should put in a flag to print it out after all the checks. Something like below

for i in range(min,max+1):
    if i > 1:
        prime = True
        for j in range(2,i):
            if (i%j) == 0:
                prime = False
                break
        if prime:
            print(i)

Upvotes: 0

Never too late
Never too late

Reputation: 83

The 2 dimension loop is whats wrong with this code , when i = 5 , you go for j (2,5) so you go through the loop three times, you should add a command to prevent a repetition

Upvotes: 0

Related Questions