**Version:*** 1.0.3 *

**Type:** Function

**Category:** Math Functions

**License:** GNU General Public License

**Description:** This is the fastest prime code. There's only one parameter; $limit.

<?php // floor and count added /*killabunny@seductive.com added the following: /* Took the square root out of the loop (it was a bottleneck to calculate it every time) /* Optimized the prime number test a bit, whereby all numbers can be excluded as follows: /* X - 1 < N < X + 1, where X is any factor of 6 and N is the number to be tested ($to_test). /* This is performed by adding either 4 or 2 to the previous prime number, depending on its /* modulus of 6. See the line: $i = (($to_test % 6) == 5)?2:4; below. */ function get_prime($floor, $limit) { //BEGIN FUNCTION $count=0; $to_test = $floor; //'i' is used as an increment of either 2 or 4, depending on the previous prime. $i = 0; while($to_test < $limit) { $testdiv = 2; //took the square root out of the loop: $to_test_root = sqrt($to_test); $was_prime = FALSE; while (TRUE) { if ($testdiv > $to_test_root) { print "$count - $to_test\n<br>"; $count++; $was_prime = TRUE; break; } if ($to_test % $testdiv == 0) { break; } $testdiv++; } //Primes 2, 3 and 5 are excluded from this test: if ($was_prime AND $to_test > 5){ $i = (($to_test % 6) == 5)?2:4; $to_test+=$i; } else { //not a prime, so the test doesn't apply. $to_test++; } } //END FUNCTION } get_prime(4000,6000); ?>