« SugarCRM | Home | Prime number detector: sieve method »

Prime number detector: brute force method

By Sparky | December 6, 2005

Tonight I continued my development efforts and implemented a simple brute force algorithm that detects if a given number is prime. You can see it in action or check out the code I used:

$max = (int)(sqrt($totest) + 1); //set the max value to test
$isprime = true; //initialize the $isprime variable
for ($i = 2; $i <= $max; $i++) { //for loop from 2 to $max
//Determine if $totest is divisible by $i
if (fmod($totest, $i) == 0) { //is there a remainder?
$isprime = false; //the number is not prime
$i = $max; //exit the loop
}
}

Neat huh? Not too complicated but fun to do. Next I’m going to implement a sieve algorithm to determine if a series of numbers is prime or not.

Share and enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • E-mail this story to a friend!
  • bodytext
  • del.icio.us
  • Fark
  • StumbleUpon
  • Technorati
  • Facebook

Topics: Development, Technology |

Comments