Primality by trial division

From Rosetta Code
Revision as of 23:11, 20 November 2007 by rosettacode>Mwn3d (→‎{{header|Ruby}}: Forgot a space.)
Task
Primality by trial division
You are encouraged to solve this task according to the task description, using any language you may know.

Write a boolean function that tells whether a given integer is prime. Remember that 1 and all non-positive numbers are not prime.

Ruby

def prime(a)
  if a==2
   return true
  end

  if a<=1 || a%2==0
    return false
  end

  d=3
  while d <= Math.sqrt(a) do
    if a%d==0
      return false
    end
    d+=2
  end

return true
end

Java

public static boolean prime(long a){
   if(a == 2){
      return true;
   }else if(a <= 1 || a % 2 == 0){
      return false;
   }
   for(long n= 3; n <= (long)Math.sqrt(a); n+= 2){
      if(a % n == 0){ return false; }
   }
   return true;
}