I'm currently trying to make a simple primality test using python to test prime number.
Here is the code I've made for the test:
def is_prime(n):
if np.mod(n, 2) == 0:
return False
f = 3
while np.square(f) <= n:
if np.mod(n, f) == 0:
return False
f += 2
return True
I run the code, and it works fine for small numbers. Then I enter a huge number (for convenience, I chose 2^128
), it returns True. But when I enter 2^129
, 2^130
, 2^131
, 2^132
(and so on), it always returns True. I believe my loop has been skipped. To verify this, I modified the code like below:
while np.square(f) <= n:
if np.mod(n, f) == 0:
print(f) #Added line
return False
f += 2
print(f) #Added line
I test this again for some small numbers, and it'll print the correct value of f. But for arbitrarily large numbers (higher than '2^50', maybe), it'll only print 3 (the initial value of f). So I am sure that this while loop has been skipped.
Is there a way to fix this?
P/S:
I've also made other primality test. But I want to use this test as a verification for the result of those tests (though it'll take longer)
I also using Numba to speed up my code (
@jit(nopython=True)
). This is why I use a lot of np function, as Numba work efficiency with NumPy
Edit 1:
- I have re-test the code without, and it works perfectly fine (even with massive numbers) but it much slower. So I guess there is a problem with Numba when handling a large number