Primality by trial division: Difference between revisions

From Rosetta Code
Content added Content deleted
(Logo)
(added ocaml)
Line 4: Line 4:


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

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
main:(
main:(
Line 66: Line 67:


=={{header|C}}==
=={{header|C}}==
#include <math.h>
<c>#include <math.h>
#define FALSE 0
#define FALSE 0
#define TRUE 1
#define TRUE 1
int isPrime( unsigned int n )
int isPrime( unsigned int n )
{
{
unsigned int i;
unsigned int i;
if ( n == 2 )
if ( n == 2 )
return TRUE;
return TRUE;
if ( n <= 1 || ( n & 1 ) == 0 )
if ( n <= 1 || ( n & 1 ) == 0 )
return FALSE;
return FALSE;
for ( i = 3 ; i <= sqrt( n ) ; i += 2 )
for ( i = 3 ; i <= sqrt( n ) ; i += 2 )
if ( n % i == 0 )
if ( n % i == 0 )
return FALSE;
return FALSE;
return TRUE;
return TRUE;
}</c>
}


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 92: Line 93:


=={{header|D}}==
=={{header|D}}==
import std.math: sqrt;
<d>import std.math: sqrt;
bool isPrime(int n) {
bool isPrime(int n) {
if (n == 2)
if (n == 2)
return true;
return true;
if (n <= 1 || (n & 1) == 0)
if (n <= 1 || (n & 1) == 0)
return false;
return false;

for(int i = 3; i <= sqrt(cast(float)n); i += 2)
for(int i = 3; i <= sqrt(cast(float)n); i += 2)
if (n % i == 0)
if (n % i == 0)
return false;
return false;
return true;
return true;
}</d>
}


=={{header|Forth}}==
=={{header|Forth}}==
Line 136: Line 137:


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


=={{header|Logo}}==
=={{header|Logo}}==
Line 192: Line 193:
true
true
)
)

=={{header|OCaml}}==
<ocaml>let is_prime n =
if n = 2 then true
else if n < 2 || n mod 2 = 0 then false
else
let rec loop k =
if k * k > n then true
else if n mod k = 0 then false
else loop (succ k)
in loop 3</ocaml>


=={{header|Perl}}==
=={{header|Perl}}==
sub prime {
<perl>sub prime {
$a = shift;
$a = shift;
if ($a == 2) {
if ($a == 2) {
return 1;
return 1;
}
}
if ($a <= 1 || $a % 2 == 0) {
if ($a <= 1 || $a % 2 == 0) {
return 0;
return 0;
}
}
$d = 3;
$d = 3;
while ($d <= sqrt($a)) {
while ($d <= sqrt($a)) {
if ($a % $d == 0) {
if ($a % $d == 0) {
return 0;
return 0;
}
}
$d += 2;
$d += 2;
}
}
return 1;
return 1;
}</perl>
}


=={{header|Python}}==
=={{header|Python}}==
Line 216: Line 228:


{{works with|Python|2.5}}
{{works with|Python|2.5}}
<python>def prime(a):
<pre>
return not (a < 2 or any(a % x == 0 for x in range(2, int(a**0.5) + 1)))</python>
def prime(a):
return not (a < 2 or any(a % x == 0 for x in range(2, int(a**0.5) + 1)))
</pre>


Another test. Exclude even numbers first:
Another test. Exclude even numbers first:


<python>def prime2(a):
<pre>
def prime2(a):
if a == 2: return True
if a == 2: return True
if a < 2 or a % 2 == 0: return False
if a < 2 or a % 2 == 0: return False
return not any(a % x == 0 for x in range(3, int(a**0.5) + 1, 2))
return not any(a % x == 0 for x in range(3, int(a**0.5) + 1, 2))</python>
</pre>


Yet another test. Exclude multiples of 2 and 3, see http://www.devx.com/vb2themax/Tip/19051:
Yet another test. Exclude multiples of 2 and 3, see http://www.devx.com/vb2themax/Tip/19051:


{{works with|Python|2.4}}
{{works with|Python|2.4}}
<python>def prime3(a):
<pre>
def prime3(a):
if a < 2: return False
if a < 2: return False
if a == 2 or a == 3: return True # manually test 2 and 3
if a == 2 or a == 3: return True # manually test 2 and 3
Line 246: Line 253:
i = 6 - i # this modifies 2 into 4 and viceversa
i = 6 - i # this modifies 2 into 4 and viceversa


return True
return True</python>
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
def prime(a)
<ruby>def prime(a)
if a==2
if a==2
return true
return true
end
end

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

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

return true
return true
end
end</ruby>


=={{header|Scheme}}==
=={{header|Scheme}}==
(define (is-prime? x)
<scheme>(define (is-prime? x)
(cond ((< x 2) #f)
(cond ((< x 2) #f)
((= x 2) #t)
((= x 2) #t)
((zero? (remainder x 2)) #f)
((zero? (remainder x 2)) #f)
(else
(else
(let loop ((c 3))
(let loop ((c 3))
(cond ((> (* c c) x) #t)
(cond ((> (* c c) x) #t)
((zero? (remainder x c)) #f)
((zero? (remainder x c)) #f)
(else (loop (+ c 2))))))))
(else (loop (+ c 2))))))))</scheme>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==

Revision as of 03:02, 13 May 2008

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.

Use trial division. Even numbers may be eliminated right away. A loop from 3 to √(n) will suffice, but other loops are allowed.

Ada

<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;</ada>

ALGOL 68

main:(
  PROC is prime = ( INT n )BOOL:
  (
    IF n = 2 THEN 
      TRUE
    ELIF n <= 1 OR n MOD 2 = 0 THEN 
      FALSE
    ELSE
      BOOL prime := TRUE;
      FOR i FROM 3 BY 2 TO ENTIER sqrt(n) WHILE prime := n MOD i /= 0 DO
         SKIP
      OD;
      prime
    FI
  );
  
  INT upb=100;
  printf(($" The primes up to "g(-3)" are:"l$,upb));
  FOR i TO upb DO 
    IF is prime(i) THEN
      printf(($g(-4)$,i))
    FI
  OD;
  printf($l$)
)

Output:

The primes up to 100 are:
  2   3   5   7  11  13  17  19  23  29  31  37  41  43  47  53  59  61  67  71  73  79  83  89  97

BASIC

Works with: QuickBasic version 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

C

<c>#include <math.h>

  1. define FALSE 0
  2. define TRUE 1

int isPrime( unsigned int n ) {

   unsigned int i;
   if ( n == 2 )
       return TRUE;
   if ( n <= 1 || ( n & 1 ) == 0 )
       return FALSE;
   for ( i = 3 ; i <= sqrt( n ) ; i += 2 )
       if ( n % i == 0 )
           return FALSE;
   return TRUE;

}</c>

Common Lisp

(defun primep (a)
 (cond ((= a 2) T)
       ((or (<= a 1) (= (mod a 2) 0)) nil)
       ((loop for i from 3 to (sqrt a) by 2 do
               (if (= (mod a i) 0)
                   (return nil))) nil)
       (T T)))

D

<d>import std.math: sqrt; bool isPrime(int n) {

   if (n == 2)
       return true;
   if (n <= 1 || (n & 1) == 0)
       return false;
   for(int i = 3; i <= sqrt(cast(float)n); i += 2)
       if (n % i == 0)
           return false;
   return true;

}</d>

Forth

: prime? ( n -- ? )
       dup 2 < if      drop false
  else dup 2 = if      drop true
  else dup 1 and 0= if drop false
  else 3
       begin 2dup dup * >=
       while 2dup mod 0=
             if       2drop false exit
             then 2 +
       repeat         2drop true
  then then then ;

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..]

J

Actually 1&p: would do, but the task calls for trial division, so:

isprime=: 3 : 'if. 3>:y do. 1<y else. 0 *./@:< y|~2+i.<.%:y end.'

Java

<java>public static boolean prime(double 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;

}</java>

to prime? :n
  if :n < 2 [output "false]
  if :n = 2 [output "true]
  if equal? 0 modulo :n 2 [output "false]
  for [i 3 [sqrt :n] 2] [if equal? 0 modulo :n :i [output "false]]
  output "true
end

LSE64

over : 2 pick
2dup : over over
even? : 1 & 0 =

# trial n d yields "n d 0/1 false" or "n d+2 true"
trial : 2 +                 true
trial : 2dup % 0 =   then 0 false
trial : 2dup dup * < then 1 false
trial-loop : trial &repeat

# prime? n yields flag
prime? : 3 trial-loop >flag drop drop
prime? : dup even? then drop false
prime? : dup 2 =   then drop true
prime? : dup 2 <   then drop false

MAXScript

fn isPrime n =
(
    if n == 2 then
    (
        return true
    )
    else if (n <= 1) OR (mod n 2 == 0) then
    (
        return false
    )

    for i in 3 to (sqrt n) by 2 do
    (
        if mod n i == 0 then return false
    )
    true
)

OCaml

<ocaml>let is_prime n =

 if n = 2 then true
 else if n < 2 || n mod 2 = 0 then false
 else
   let rec loop k =
     if k * k > n then true
     else if n mod k = 0 then false
     else loop (succ k)
   in loop 3</ocaml>

Perl

<perl>sub prime {

 $a = shift;
 if ($a == 2) {
   return 1;
 }
 if ($a <= 1 || $a % 2 == 0) {
   return 0;
 }
 $d = 3;
 while ($d <= sqrt($a)) {
   if ($a % $d == 0) {
     return 0;
   }
   $d += 2;
 }
 return 1;

}</perl>

Python

The simplest primality test, using trial division:

Works with: Python version 2.5

<python>def prime(a):

   return not (a < 2 or any(a % x == 0 for x in range(2, int(a**0.5) + 1)))</python>

Another test. Exclude even numbers first:

<python>def prime2(a):

   if a == 2: return True
   if a < 2 or a % 2 == 0: return False
   return not any(a % x == 0 for x in range(3, int(a**0.5) + 1, 2))</python>

Yet another test. Exclude multiples of 2 and 3, see http://www.devx.com/vb2themax/Tip/19051:

Works with: Python version 2.4

<python>def prime3(a):

   if a < 2: return False
   if a == 2 or a == 3: return True # manually test 2 and 3   
   if a % 2 == 0 or a % 3 == 0: return False # exclude multiples of 2 and 3
   maxDivisor = a**0.5
   d, i = 5, 2
   while d <= maxDivisor:
       if a % d == 0: return False
       d += i 
       i = 6 - i # this modifies 2 into 4 and viceversa
   return True</python>

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

Scheme

<scheme>(define (is-prime? x)

 (cond ((< x 2) #f)
       ((= x 2) #t)
       ((zero? (remainder x 2)) #f)
       (else
         (let loop ((c 3))
           (cond ((> (* c c) x) #t)
                 ((zero? (remainder x c)) #f)
                 (else (loop (+ c 2))))))))</scheme>

TI-83 BASIC

Calculator symbol translations:

"STO" arrow: →

Square root sign: √

Prompt A
If A=2:Then
Disp "PRIME"
Stop
End

If (fPart(A/2)=0 and A>0) or A<2:Then
Disp "NOT PRIME"
Stop
End

1→P
For(B,3,√(A))
If FPart(A/B)=0:Then
0→P
√(A)→B
End
B+2→B
End

If P=1:Then
Disp "PRIME"
Else
Disp "NOT PRIME"
End