DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Im a freelance developer for Web apps and Artificial intelligence (in Python). Budy K. has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Step-by-step Logic Finding Prime numbers with PHP

  • submit to reddit
function prime($n){
      //all numbers that will be evaluated as prime       
               $counter = 0; 
              //all probability of divisible factors
                    //$i is divisible by $j, increament the counter
                     if($i % $j==0){                       
           /*how many greens? they have to be 2 
            ( each prime number has exactly 2 (two) divisors)*/
                 print $i." is Prime <br/>";

prime(20);  //find the Prime for 1-20 range

A Prime numbers are all integers(number) that can be divided evenly only by 1 AND itself.
And it must be a whole number greater than 1. 

  2           3       /   \        /  \     ...................1   2      1  3

Logic in Program

Prime Logic

Take a look above, the green numbers indicate that each prime number has exactly 2 (two) divisors. 1 and itself. From this simple logic, we can easily code it . Take a look again in Snippet above

Notes: This example is just for those who are new to this