Sunday, 8 January 2012

Submitted a new PHP class: IsPrime

I posted a new PHP class on phpclasses.org called IsPrime and it just tests to see if a number is prime or not using some simple tests/sieves before it does the usual processor-intensive test. Most solutions just quickly jump into the processor intensive method while this approach should prove a much faster way to determine if a number is prime or not.

Test 1: is the number positive - primes must be positive
Test2: is the number a single digit prime - 2,3,5,7
Test3: does the number end in 1, 3, 7 or 9 as all prime numbers do
Test4: is the number divisible by 3 or 7 - most numbers that end with 1, 3, 7 or 9 are divisible by those and are therefore not prime
Test5: is the number divisible by another prime number - if it is then it's not prime. This is the processor intensive test.

If it passes those five steps then it's prime. Here's the class: http://www.phpclasses.org/package/7281-PHP-Check-whether-a-number-is-prime.html

No comments:

Post a Comment