Prolog Program To Check If A Number Is Prime

前端 未结 2 1738
悲哀的现实
悲哀的现实 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:21

    I'm a beginner in Prolog but managed to fix your problem.

    divisible(X,Y) :- 0 is X mod Y, !.
    
    divisible(X,Y) :- X > Y+1, divisible(X, Y+1).
    
    isPrime(2) :- true,!.
    isPrime(X) :- X < 2,!,false.
    isPrime(X) :- not(divisible(X, 2)).
    

    The main issue was the statement X mod Y is 0. Predicate is has two (left and right) arguments, but the left argument has to be a constant or a variable that is already unified at the moment that the predicate is executing. I just swapped these values. The rest of the code is for checking number 2 (which is prime) and number less than 2 (that are not primes)

    I forgot to mention that the comparison Y < X is buggy, because you want to test for all numbers between 2 and X-1, that comparison includes X.

提交回复
热议问题