Your issue is that you are only checking one single set of p
and q
, so you only get the "not a prime number"
output if you are very lucky and p*q
happens to equal anumber
on that first go.
The way that most very-simple prime-checkers works is to go sequentially between 0 and the square root of the test number, for both p and q, and rule out all possible factors. There are loads of other ways of checking for primarity though.
However, because computers are fast, you can keep the random choices, and just try a few thousand times, for small numbers the chances are you will probably be correct! Going through properly is still the best way.
(Disclaimer - this is not a real solution, just an example of using random
in a more-correct way)
I've added a for loop to your code, which if it finds a match, will print and then do an early return from the function, or if it still hasn't found a hit after 10000 random tries, says that is is maybe prime.
import random
def primechecker(anumber):
if anumber <= 1:
print('1 is not a prime number, \n*2Input a positive integer greater than 1')
for _ in range(10000):
p = random.randint(2,anumber)
q = random.randint(2,anumber)
if p*q==anumber:
print('%d is not a prime number'%anumber)
return
print('%d is maybe a prime number ! :-)'%anumber)
primechecker(70)import random
def primechecker(anumber):
if anumber <= 1:
print('1 is not a prime number, \n*2Input a positive integer greater than 1')
for _ in range(10000):
p = random.randint(2,anumber)
q = random.randint(2,anumber)
if p*q==anumber:
print('%d is not a prime number'%anumber)
return
print('%d is probably a prime number ! :-)'%anumber)
primechecker(70)
import random
def primechecker(anumber):
if anumber <= 1:
print('1 is not a prime number, \n*2Input a positive integer greater than 1')
for _ in range(10000):
p = random.randint(2,anumber)
q = random.randint(2,anumber)
if p*q==anumber:
print('%d is not a prime number'%anumber)
return
print('%d is probably a prime number ! :-)'%anumber)
primechecker(7)
primechecker(99)
primechecker(90)
Give it a try here -> https://repl.it/@LukeStorry/63038315
As you can see, it isn't very accurate for larger numbers, the way to go would be to not use random, but go sequentially, but this is a nice thing to try if you're learning python.