Jump to content

PHP Prime Number Method

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Megak

Megak

    Newbie

  • Members
  • PipPip
  • 16 posts

function isPrime($test) {

$prime = 1;

if ($test % 2 == 0 && $test != 2){

return 0;

} 

if ($test == 2 || $test == 3) {

return 1;

}

for ($try = 3; $try < $test; $try++){

if (($test % $try) == 0) {

$prime = 0;

}

}

return $prime;

}

Not the most efficient way to do it, but it's simple and gets the job done and returns a 1 or 0 depending on whether the specified number is prime or not.

Enjoy! :)

Edited by Megak, 22 April 2011 - 12:02 PM.


#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
There are certain numbers that are never primes. For example an even number is never prime(Except 2), so you might as well increase the 'try' by 2 instead of 1, checking only odd numbers.
numbers ending with 0 or 5 are never prime, because they divide with 5. and so on...

#3
Megak

Megak

    Newbie

  • Members
  • PipPip
  • 16 posts

Sinipull said:

There are certain numbers that are never primes. For example an even number is never prime(Except 2), so you might as well increase the 'try' by 2 instead of 1, checking only odd numbers.
numbers ending with 0 or 5 are never prime, because they divide with 5. and so on...

yea, i have been aware of this ever since I made these methods on various platforms. I edited the method just now to read that only odds will be tested, but testing the divides by 3, 5, 7 thing only works up to 7 before it becomes ineffective and inefficient.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users