0

i wrote this program to check weather the no. is prime or not but it shows the number is prime multiple times. how can i solve it

To check weather the number is prime or not.

num = int(input("please enter the number you want to check\n"))

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            print("the number is not prime")
            print(str(i) + " times " + str(num//i) + " is "+ str(num))
            break
        else:
            print("the number is prime")
elif(num == 1):
    print("the number is not prime")
else:
    print('enter a positive value')
Sociopath
  • 13,068
  • 19
  • 47
  • 75
Puneet56
  • 126
  • 1
  • 9
  • https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime – khelwood Jun 12 '19 at 08:56
  • @khelwood I think he understands the concept, but he is searching for the bug in his code – Finomnis Jun 12 '19 at 08:57
  • remove `else` block and write `print` statement outside `for` loop – Sociopath Jun 12 '19 at 08:57
  • Try to find by yourself -with a debugger- why `4` is considered as a prime number. – Arnaud Denoyelle Jun 12 '19 at 08:58
  • The `else` block should probably be indented on the same level as the `for` in order to make a `for-else` construct. If you simply place the statement outside the loop, it will print it even when the loop breaks – shriakhilc Jun 12 '19 at 08:59
  • Possible duplicate of [What is the best algorithm for checking if a number is prime?](https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime) – dome Jun 12 '19 at 09:03
  • @dome Don't think so, I interpret his question not as an algorithmical question of how to check, but as a bug hunt in his code – Finomnis Jun 12 '19 at 09:04
  • Yes, you are right, I remove the flag. – dome Jun 12 '19 at 09:06

6 Answers6

2

Here is my code to check whether a number is prime or not, hope it helps

# Program to Check whether given number is prime

def isPrime(number):
    limit = int(number/2) # limit indicates how many times we need to run the loop
    flag=0                # to keep track whether the number is prime or not
    if number==0 or number==1:
        print(f"The Given Number {number} is Not Prime")
        return
    for i in range(2,limit+1):
        if number%i==0:
            flag=1
            break
    if flag==0:
        print(f"The Given Number {number} is Prime")
    else:
        print(f"The Given Number {number} is Not Prime")

isPrime(1)

Anurag
  • 21
  • 4
1

Your problem is that the else part of your for-loop is wrong. You print "the number is prime" every time a division check fails, not just at the end.

I added an isPrime boolean that tracks if a single check failed. Only if none of them fail, you can print that the number is prime.

num = int(input("please enter the number you want to check\n"))

if num > 1:
    isPrime = True
    for i in range(2, num):
        if (num % i) == 0:
            print("the number is not prime")
            print(str(i) + " times " + str(num//i) + " is "+ str(num))
            isPrime = False
            break
    if isPrime:
        print("the number is prime")
elif(num == 1):
    print("the number is not prime")
else:
    print('enter a positive value')

You can simplify that even more, with a construct of python called for-else (credits to @TheGamer007):

num = int(input("please enter the number you want to check\n"))

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            print("the number is not prime")
            print(str(i) + " times " + str(num//i) + " is "+ str(num))
            break
    else:
        print("the number is prime")
elif(num == 1):
    print("the number is not prime")
else:
    print('enter a positive value')

It works because Python's for-loops can have an else: following, which only triggers if you don't break out of the loop.

This might be exactly what you were trying to do. In that case, all you did wrong was your indentation.

Also, from an algorithmical point of view, there are much better ways to check. A first simple improvement is that you don't need to check range(2,num), but only range(2, int(math.sqrt(num))+1)

Finomnis
  • 18,094
  • 1
  • 20
  • 27
  • You can skip the additional `isPrime` variable if you use a [`for-else`](http://book.pythontips.com/en/latest/for_-_else.html) block. It will execute only if the loop wasn't broken out of. Could have been OP's original intent as well. – shriakhilc Jun 12 '19 at 09:12
  • 1
    Oh, to be honest, after years of python programming, this is the first time i heard of the for-else construct. Fascinating. I'll update the answer. – Finomnis Jun 12 '19 at 11:48
  • I felt the same way when I first found it here on SO. – shriakhilc Jun 12 '19 at 11:50
0

Use a variable, for example flag and initialize it to 0. If the number is not prime,i.e i%2==0 set flag to 1 and break, else flag = 0 .

After that come out of the for block, and with the help of if condition display the number is prime or not. That is if flag==0 the number is prime else not.

Yash Anand
  • 29
  • 1
  • 9
0

All you need in order to determine whether a number is prime or not, is to find 1 number that is greater or equal to 2 that divides the number.

In your loop, you print out a message that says "the number is prime" for each number that does not divide the given number.

For example, if you want to check whether the number 9 is prime or not, you will loop all numbers from 2 to 8 and check if they can divide 9. So in your for loop, the number 5 for instance -> 9%5 != 0 -> "the number is prime" message will pop up, which is wrong.

The code below shows how you can use a boolean to rise up a flag when the number is NOT prime.

num = int(input("please enter the number you want to check\n"))
isPrime = True
while num < 1:
    int(input("enter a positive value\n"))
if num == 1:
    print("the number is not prime")
    return
for i in range(2, num):
    if (num % i) == 0:
       isPrime = False
       break
print(str(num) + " is prime? " + str(isPrime))
RanAB
  • 397
  • 1
  • 4
  • 16
0

I would suggest the following implementation

We only need to check/loop up to a square root of the number and not the number itself and is thus faster.

The for-else structure gets you rid of the isPrime flag that you otherwise need. The way this works is that if the loop finishes normally without breaking (meaning you haven't found what you are looking for) it goes into the else

import math

num = int(input("please enter the number you want to check\n"))

if num > 1:
    for i in range(2, int(math.sqrt(num))+1):
        if (num % i) == 0:
            print("the number is not prime")
            print(i, "times", num//i, "is", num)
            break                                                     
    else:        
        print("the number is prime")
else:                                
    print("the number is not prime")
0

One way to do it:

def is_prime(n):
    count = 0
    if x > 1:
        for i in range(1, n + 1):
             if x % i == 0:
                  count += 1
    return count == 2



number = int(input("Insert a number: "))
   if is_prime(number):
      print(str(number) + " is a prime number")
   else:
      print(str(number) + " is not a prime number!")

is_prime(7) # >> Returns True

How does it work:

A prime number (n) must fullfill the following rules:

  1. n > 1;
  2. n divisible only to 1 and itself( n % 1 == 0, n % n == 0)

Perform the modulus operation from 1 to n iteratively. Increment the variable count every time the result is 0. If the input satisfies the 2nd condition from above then count should be equal 2. If count equals 2 then the number is prime.

Ex:

is_prime(7): 7 % 1 = 0 (count += 1), 7 % 2 = 1, 7 % 3 = 1, 7 % 4 = 3, 7 % 5 = 2, 7 % 6 = 1, 7 % 7 = 0 (count += 1); >> 7 is prime