Naïve integer primality calculator in PHP
Bismillaahir Rahmaanir Raheem
Alhamdulillaah, while reading about integers and, subsequently, prime numbers last night, I decided the time had come for me to write a primality calculator in PHP. The test I use in my implementation is about as a naïve as one can possible get, but it was fun, nonetheless.
Interestingly enough, I discovered that there already exists a primality calculator for *nix-based systems - primes. It comes with the bsd-games package for Fedora. I assume the same is true for other distributions. Mine isn’t quite as fast yet…but it does accept, optionally, one or two arguments. If there are two arguments, then it will calculate all primes starting from the first going until the second. If there is only one argument, it will calculate from PRIME_START (defined to be 2) through to the largest integer PHP can handle on your platform (usually the maximum value of a signed int on your machine).
There are loads of potential optimizations that can be performed, and this was just something written on a whim as a proof of concept. It seems to be accurate, however. The code, released under the GNU GPL v. 3.0, can be found below.
Continue Reading »
