So I decided to learn python this weekend and I started with my default hello world, the prime solver. This code shouldn’t work… But for whatever reason it does (for numbers 5 and higher.)
#!/usr/bin/python
a = 2
while a < 65535:
c = 0
a = a + 1
b = 2
while b != a:
if a % b == 0:
#print a, "is not prime. LCD is ", b
break
b = b + 1
if a - 1 == b: c = 1
if c == 1: print a, " is prime"
The next to the last conditional should always be false, and yet somehow a -1 == b for all primes 5 and up.
Can someone point out this noob’s mistake, because I’m obviously missing something easily described.
Answers further below.
If
ais not prime, it has atleast two proper divisors, and of one of them must be smaller than the square root (or both are the square root). Ifbreachessqrt(a)+1, thenamust be prime. So ifbreachesa - 1, you can be pretty sure it’s prime. You could also replace it byif a - 3 == b, ora / 2(but this might not work for the smaller primes).