1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

合成数の和(advent calendar 2018,Prolog)

Last updated at Posted at 2018-12-20

advent calendar 12/19を見ましたら埋まっていませんでしたし、
Prologの日もありませんでしたので至急コードを書きました。
Fが合成数ならリストに加えF+1を評価しリストの長さがNなら合計して終了です。

%swi-Prolog  version 7.4.2
%solve(100,R). %など
%:-initialization(solve(100,R)).  % ideone

syn(X):-floor(sqrt(X),Y),between(2,Y,N),X mod N =:=0,!.

solve(N,_,L,R):-length(L,N),sumlist(L,R),write(R).
solve(N,F,L,R):-(syn(F)->L1=[F|L];L1=L),F1 is F+1,solve(N,F1,L1,R).
solve(N,R):-solve(N,4,[],R),!.

(追加)
Prologは戻り値が他の言語のような形では帰りませんので習慣でsolve(N,R)と書きましたが、
write/1があればRはいりませんので、そちらも載せます。

%solve(100). %など
%:-initialization(solve(100)).

syn(X):-floor(sqrt(X),Y),between(2,Y,N),X mod N =:=0,!.

solve(N,_,L):-length(L,N),sumlist(L,R),write(R).
solve(N,F,L):-(syn(F)->L1=[F|L];L1=L),F1 is F+1,solve(N,F1,L1).
solve(N):-solve(N,4,[]),!.
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?