I've been trying to do a Prolog problem to generate the prime numbers from 1 to N but it keeps replying with true or false and i cannot find the error. Query example: generatePrime(10, X)
isPrime( 2 ) .
isPrime( P ) :-
P > 2 ,
isDivisible( P , P-1 ) .
isDivisible( P , X ) :-
X > 1,
P mod X =\= 0 ,
isDivisible( P , X-1 ) .
isDivisible( _ , X ) :-
1 is X .
generatePrime( N , X ) :-
not( isPrime( N ) ) ,
Z is N-1 ,
generatePrime( Z , X ) .
generatePrime(N, X):-
isPrime( N ) ,
X is N ,
Z is N-1 ,
generatePrime( Z , X ) .
generatePrime( 1 , X ) :-
X is 1 .
I think you want to build a list:
generatePrime( 1 , [] ) :- !.
generatePrime( N , X ) :-
not( isPrime( N ) ) , !,
Z is N-1 ,
generatePrime( Z , X ) .
generatePrime(N, [N | X] ):-
Z is N-1 ,
generatePrime( Z , X ) .
I did not test it but something like this should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.