简体   繁体   中英

checking prime number in python

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')

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)

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)

Use a variable, for example flag and initialize it to 0. If the number is not prime,ie 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.

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))

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM