Is the function isprime deterministic?
5 views (last 30 days)
Rafael S.T. Vieira on 20 Jun 2020
I was playing with primes, and I was happy to verify that
works. However, I wanted to test a huge prime, and found that (2ˆ64)-59 is prime according to SageMath and Wolfram Alpha. However MATLAB function is prime returns false.
Which one is right? The documentation of the function isprime seems to suggest that it is deterministic, but it would be nice to say it explicitly. Anyone would, please, confirm it?
John D'Errico on 20 Jun 2020
Edited: John D'Errico on 20 Jun 2020
Your problem is that number is NOT represented in MATLAB as you think it is. MATLAB CANNOT represent a number as a double exactly when the integer is larger than 2^53-1. Double precision is limited in that respect. And yes, I know you THINK you created the number 2^64-59 as a uint64. You did not.
So, YES, I believe it can be shown that isprime is deterministic within the limits of double precision. However, NO, if you throw numbers at it that are too large, then it will fail. The biggest reason why isprime failed for you was that you created it as a double precision number, AND only then converted to uint64. 2^64 is NOT a number you can trust, because it is created as a double.
There is another problem, even more serious. Can you even compute 2^64, and store it in a uint64 variable? NO!
Should 2^64 be an odd number? Of course not, yet as you see, 2^64 overflows even a uint64 variable.
Instead, use sym, which her will be quite efficient.
See that I created 2 as a symbolic number, only then raising it to a power.
If I did not have the symbolic toolbox, I could have done this - subtly avoiding any overflows, because I recognize that intmax('uint64') is just 2^64-1.
isprime(intmax('uint64') - 58)
Now it works. the symbolic toolbox isprime is MUCH faster, although I expect it is really best called isprobable prime for large integers, since it will be based on a multiple set of calls to a MIller-Rabin test, and possibly other tricks. I recall looking up the basis of the mathematica isprime test, which is similar. A true test for primality that cannot be fooled is more difficult to achieve, and will be MUCH slower running most of the time.
By the way, what number did you test to see if it was prime?
uint64(2^64) - 59
intmax('uint64') - 58
You should see clearly why MATLAB thought the former version was not prime. After all, most even numbers are not prime. Almost all of them, in fact.