簡體   English   中英

如何從列表中獲取質數並將它們放入空列表中

[英]How to get prime numbers from list and put them in empty list

我想從數字列表中獲取所有質數並將其放入另一個空列表中。 我的問題是,只要函數 isPrime 為 false,程序就會終止。 我是序言的初學者,所以如果您有任何反饋,我將不勝感激。 這是我的代碼如下:

check_prime(X):-
     Xtemp is integer(X/2),
     isPrime(X,Xtemp).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
isPrime(_,2).
isPrime(2,_).
isPrime(Num,Counter):-
     X is Counter-1,
     X \= 0,
     X2 is mod(Num,X),
     X2 \= 0,
     isPrime(Num,X).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
prime_list([],Y).
prime_list([H|T],[H|T2]):-
     check_prime(H),
     prime_list(T,T2).

即使對於非質數,您的 check_prime 函數也會給出 true 。 示例:check_prime(4) 會調用 isPrime(4, 2),它會與 isPrime 的第一個子句統一起來。

為您提供素數列表的代碼示例如下:

% predicate to check if X has any divisors
divisible(X,Y) :- 0 is X mod Y, !.
divisible(X,Y) :- X > Y+1, divisible(X, Y+1).

%predicate to check if that number is prime by using the divisible predicate
isPrime(2) :- true,!.
isPrime(X) :- X < 2,!,false.
isPrime(X) :- not(divisible(X, 2)).

%predicate that returns the resulted list
primeList([], []). % stopping condition, when list empty
% we add current element to the resulting list if it is prime 
primeList([H|T], [H|R]):- isPrime(H), !, primeList(T, R). 
% otherwise, we just skip it
primeList([_|T], R):- primeList(T, R). 

查詢:?-primeList([1,2,3,4,5,6,7,8,9], R)。 => R=[2,3,5,7]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM