(919) 964-9842
(919) 964-9842

# PHP Coding Tests: Find All Prime Numbers Up to 100

Yet another coding test and another fail-boat by me! I tried to rack my brain around this one but my on-the-spot math skills are limited. I don't know why I blank on these during the process, but I was given time on my own to figure it out. I took that opportunity, even if it doesn't mean the job, to make sure I can do basic math.

You can insert any number to find the prime number to, but in this case, we're doing 100.

 12345678910111213141516171819202122 // total number to loop through \$total = 100; // 1 is always prime and its weird so here it is echo 1 . "\n"; // loop through the total number provided to go through for(\$i = 2; \$i <= \$total; \$i++) {   // loop through each number up to the number we are currently going through   // ie. if its 4, we want to loop through 2, 3, 4   // skipping 1 because everything is divisible by 1   for(\$j = 2; \$j <= \$i; \$j++) {     // if the current number matches the counted up number     // we've hit the end and can consider this prime     if(\$i == \$j) {       echo \$i . "\n";     }     // checks each number using modulo     // ie. if there is NOT a remainder, then this isnt prime     if(\$i % \$j == 0) {       break;     }   } }

Comments spell it out above. Let me know what you think!

Categories: Development