Primality by trial division

From Rosetta Code
Revision as of 12:32, 21 November 2007 by rosettacode>Dirkt (Clarified task; added Haskell example)
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.

Implement the simplest primality test, using trial division.

Ada

function Is_Prime(Item : Positive) return Boolean is
   Result : Boolean := True;
   Test : Natural;
begin
   if Item /= 2 and Item mod 2 = 0 then
      Result := False;
   else
      Test := 3;
      while Test < Integer(Sqrt(Float(Item))) loop
         if Item mod Test = 0 then
            Result := False;
            exit;
         end if;
         Test := Test + 2;
      end loop;
  end if;
  return Result;
end Is_Prime;

BASIC

Compiler: QuickBasic 4.5

Going with the classic 1 for "true" and 0 for "false":

FUNCTION prime% (n!)
  IF n = 2 THEN prime = 1
  IF n <= 1 OR n MOD 2 = 0 THEN prime = 0
  FOR a = 3 TO INT(SQR(n)) STEP 2
    IF n MOD a = 0 THEN prime = 0
  NEXT a
  prime = 1
END FUNCTION

Haskell

Without square roots:

divides k n = n `mod` k == 0

isPrime :: Integer -> Bool
isPrime n | n < 2 = False
isPrime n         = not $ any (`divides` n) $ takeWhile (\k -> k*k <= n) [2..]

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;
}

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