Prolog Program To Check Whether a Given Number Is Prime Or Not.

Prolog program to check whether a given number is prime or not.

check whether a given number is prime or not.
check whether a given number is prime or not.

Program:

% is_prime(P) :- P is a prime number
%    (integer) (+)

is_prime(2).
is_prime(3).
is_prime(P) :- integer(P), P > 3, P mod 2 =\= 0, \+ has_factor(P,3).  

% has_factor(N,L) :- N has an odd factor F >= L.
%    (integer, integer) (+,+)

has_factor(N,L) :- N mod L =:= 0.
has_factor(N,L) :- L * L < N, L2 is L + 2, has_factor(N,L2).

Output:

?- is_prime(2).
true .

?- is_prime(11).
true.

?- is_prime(77).
false.

Comments