Primality by trial division: Difference between revisions

→‎{{header|Prolog}}: generate or test
(Updated all D entries)
(→‎{{header|Prolog}}: generate or test)
Line 1,556:
 
=={{header|Prolog}}==
The following predicate showcases Prolog's support for writing predicates suitable for both testing and generating. In this case, assuming the Prolog implemenation supports indefinitely large integers, prime(N) can be used to generate primes until memory is exhausted.
<lang Prolog>prime(2).
prime(N) :- integer(N), N > 1,
between(3, inf, N),
M is floor(sqrt(N+1)), % round-off paranoia
1 is N mod 2 > 0, % is odd
M is floor(sqrt(N+1)), % round-off paranoia
check_by_odds(N, M, 3).
Max is (M-1) // 2, % integer division
forall( between(S21,M2 Max,X I), N mod (2*XI+1) > 0 ).
</lang>
Example using SWI-Prolog:
<pre>?- time( (bagof( P, (prime(P), ((P > 100000, !, fail); true)), Bag),
length(Bag,N),
last(Bag,Last),
writeln( (N,Last) ) )).
 
% 1,724,404 inferences, 1.072 CPU in 1.151 seconds (93% CPU, 1607873 Lips)
check_by_odds(N, M, S) :-
Bag = [2, 3, M25, is7, (M-1)11, //13, 217, S2 is19, S // 223|...],
N = 9592,
forall( between(S2,M2,X), N mod (2*X+1) > 0 ).
Last = 99991.
 
?- time( prime(99991) ).
/*
% 165 inferences, 0.000 CPU in 0.000 seconds (92% CPU, 1213235 Lips)
check_by_odds(N, M, F) :- F > M.
true.
check_by_odds(N, M, F) :- F =< M,
 
N mod F > 0,
?-</pre>
F1 is F + 2, % test by odds only
check_by_odds(N, M, F1).*/ </lang>
 
=={{header|PureBasic}}==
2,526

edits