Almost prime: Difference between revisions
Content deleted Content added
→{{header|Prolog}}: for k in 1 to 5 |
→{{header|Prolog}}: simplify generation of primes |
||
Line 402:
take(Take, Sorted, List).
</lang>That's it. The rest is machinery. For portability, a compatibility section is included below.
<lang Prolog>nPrimes( M, Primes) :- nPrimes( [2], M, Primes).
generate(3, N),▼
1 is N mod 2, % odd▼
M is floor(sqrt(N+1)), % round-off paranoia ▼
next_prime(Accumulator, Prime),
append(Accumulator, [Prime], Next),
▲nPrimes(Count, Primes) :-
length(Next, N),
( N = I -> Primes = Next; nPrimes( Next, I, Primes)).
N is N0 + 1,▼
% next_prime(+Primes, NextPrime) succeeds if NextPrime is the next
% multiply( +A, +List, Answer)▼
% prime after a list, Primes, of consecutive primes starting at 2.
next_prime([2], 3).
next_prime([2|Primes], P) :-
last(Primes, PP),
forall( (member(Prime, [2|Primes]),
(Prime =< Max -> true
; (!, fail))), N mod Prime > 0 ),
!,
P = N.
▲% multiply( +A, +List, Answer )
multiply( A, [], [] ).
multiply( A, [X|Xs], [AX|As] ) :-
Line 431:
multiply(A, Xs, As).
% multiplylist( L1, L2, List ) succeeds if List is the concatenation of X * L2
% for successive elements X of L1.
multiplylist( [], B, [] ).
Line 457:
:- endif.
:- if(current_prolog_flag(dialect,
append([],L,L).
append([X|Xs], L, [X|Ls]) :- append(Xs,L,Ls).
last([X], X).
last([_|Xs],X) :- last(Xs,X).
:- endif.
:- if(current_prolog_flag(dialect, gprolog)).
generate(Min, I) :-
current_prolog_flag(max_integer, Max),
Line 478 ⟶ 484:
?- time( (almostPrime(5, 10, L), writeln(L))).
[32,48,72,80,108,112,120,162,168,176]
% 1,
</pre>
|