Prolog Program To Check If A Number Is Prime

前端 未结 2 1773
悲哀的现实
悲哀的现实 2020-12-18 03:02

I wrote the following program based on the logic that a prime number is only divisible by 1 and itself. So I just go through the process of dividing it to all numbers that a

2条回答
  •  死守一世寂寞
    2020-12-18 03:15

    This answer is a follow-up to @lefunction's previous answer.

    isPrime2/1 is as close as possible to isPrime1/1 with a few changes (highlighted below):

    isPrime2(2) :-
        !.
    isPrime2(3) :-
        !.
    isPrime2(X) :-
        X > 3,
        X mod 2 =\= 0,
        isPrime2_(X, 3).
    
    isPrime2_(X, N) :-
        (  N*N > X
        -> true
        ;  X mod N =\= 0,
           M is N + 2,
           isPrime2_(X, M)
        ).
        

    Let's query!

    ?- time(isPrime1(99999989)).
    % 24,999,999 inferences, 3.900 CPU in 3.948 seconds (99% CPU, 6410011 Lips)
    true.
    
    ?- time(isPrime2(99999989)).
    % 5,003 inferences, 0.001 CPU in 0.001 seconds (89% CPU, 6447165 Lips)
    true.
    

提交回复
热议问题