File: sieve.pl

package info (click to toggle)
swi-prolog 9.0.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 82,408 kB
  • sloc: ansic: 387,503; perl: 359,326; cpp: 6,613; lisp: 6,247; java: 5,540; sh: 3,147; javascript: 2,668; python: 1,900; ruby: 1,594; yacc: 845; makefile: 428; xml: 317; sed: 12; sql: 6
file content (47 lines) | stat: -rw-r--r-- 1,022 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
% Benchmark prime number generation  using   the  sieve  of Eratosthenes
% algorithm with assert/retract. This benchmark tests assert/retract and
% JIT index generation and destruction.
%
% Auther: Jan Wielemaker
% Copyright: Public domain.

top :- clean, primes(10000), fail.
top.

:- if(\+current_predicate(forall/2)).
forall(Cond,Act) :- \+ ( Cond, \+ Act ).
:- endif.
:- if(\+current_predicate(ignore/1)).
ignore(Goal) :- (Goal->true;true).
:- endif.
:- if(\+current_predicate(between/3)).
:- use_module(library(between)).
:- endif.

:- dynamic prime/1, candidate/1.

clean :-
    retractall(prime(_)),
    retractall(candidate(_)).

primes(N) :-
    forall(between(2, N, I), assertz(candidate(I))),
    sieve(N).

sieve(Max) :-
    retract(candidate(First)),
    !,
    assertz(prime(First)),
    First < Max,
    sieve(First, 2, Max),
    sieve(Max).
sieve(_).

sieve(N, Mul, Max) :-
    I is N*Mul,
    I =< Max,
    !,
    ignore(retract(candidate(I))),
    Mul2 is Mul+1,
    sieve(N, Mul2, Max).
sieve(_, _, _).