我知道这个答案不完全的OP回答这个问题(我getPrimeList(N, L)
创建从零到N
所有质数的列表L
;在OP要求第一个N
素数),但......只是为了好玩......我试图实施Eratosthenes筛。
getListDisp(Top, Val, []) :-
Val > Top.
getListDisp(Top, V0, [V0 | Tail]) :-
V0 =< Top,
V1 is V0+2,
getListDisp(Top, V1, Tail).
reduceList(_, _, [], []).
reduceList(Step, Exclude, [Exclude | Ti], Lo) :-
NextE is Exclude+Step,
reduceList(Step, NextE, Ti, Lo).
reduceList(Step, Exclude, [H | Ti], [H | To]) :-
Exclude > H,
reduceList(Step, Exclude, Ti, To).
reduceList(Step, Exclude, [H | Ti], [H | To]) :-
Exclude < H,
NextE is Exclude+Step,
reduceList(Step, NextE, Ti, To).
eratSieve([], []).
eratSieve([Prime | Ti], [Prime | To]) :-
Step is 2*Prime,
Exclude is Prime+Step,
reduceList(Step, Exclude, Ti, Lo),
eratSieve(Lo, To).
getPrimeList(Top, []) :-
Top < 2.
getPrimeList(Top, [2 | L]) :-
Top >= 2,
getListDisp(Top, 3, Ld),
eratSieve(Ld, L).
我再说一遍:不是真的答案;只是为了好玩(就像OP,我试图学习Prolog)。
[Prolog查找N个素数]的可能重复(http://stackoverflow.com/questions/12446407/prolog-find-n-prime-numbers) – Prune