简体   繁体   中英

A program that's supposed to find out whether a number is prime or not isn't working as expected

I'm trying to make a program which will find if a number is prime or not with a very simple formula: divide the number(x) by 4. see if any number from 1 to x/4 divides perfectly by x. If not, x will be prime.

The program currently shows me the result from dividing x by every number from 1 to x/4. I want to do this: If there's a number that divides perfectly, print that x is not prime and end the program. Or if there's no numbers that divide by x, just say that x is prime and end the program.

I tried using booleans but then it showed every number as prime, which it should not do since the program doesn't know yet that x can be perfectly divided by 1 but will still be prime.

value = int(input("Type a number: "))

# prime = True

if value.__class__ == int:
    x = value / 4
    list = list(range(1, int(x) + 1))
    for number in list:
        y = value / number

        while y >= 0:
            y -= 1
            if y == 0:
                print(f"{value} is not prime")
                # print("yes")
                # y == -1
            elif 0 < y < 1:
                print(f"{value} is prime")
                # print("no")
    # if prime:
    #     print(f"{value} is prime")
    # else:
    #     print(f"{value} is not prime")

Your first logic is wrong. You need to check up to math.sqrt(x)

>>> import math
>>> [a/4 < math.sqrt(a) for a in range(100)]
[False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]

This will technically work beyond x=15 but then you'll be checking more numbers than you need to You can see this by looking at the graphs https://www.desmos.com/calculator/dybweqs6lk

first of all where did you find this formula?

second you didn't implement what you said in your code. you need to check all four kinds that are possible after dividing and choose the result according to all of them, not in any loop.

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