How to generate primes
Introduction
Here’s a micro guide on how to generate prime numbers in a given interval with PHP.
A prime number is a natural number (a positive integer) which has exactly two distinct natural number divisors (1 and the number itself).
The Code
What we want to do is to create a function that takes a minimum and a maximum value of primes values we want to find. Then we try to divide the number by every number bigger than 1 and smaller than itself and determine if it has a remainder on any of the calculation. If it has on every caltulation we’ve got a prime, if not, we don’t.
I’ve made the script to only use odd numbers, because 2 is the only non-odd prime.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php function prime_generator($from,$to,$return=false){ if(!($from%2)) $from++; if($from <= 2){ $from = 3; if($return) $primes .= "2, "; else echo "2, "; } for($x=$from; $x <= $to; $x+=2){ $prime=true; for($y=$x-1;$y>1;$y--){ if(!($x%$y)){ $prime=false; } } if($prime){ if($return) $primes .= $x . ", "; else echo $x . ", "; } } if($return) return $primes; } $primes = prime_generator(0,100, true); echo $primes; ?> |
You can use the function either with or without the $return parameter set. If it’s set to true it will return all primes in the given interval, if not, it gives the output right away.