How to resolve the algorithm Sieve of Eratosthenes step by step in the Logtalk programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sieve of Eratosthenes step by step in the Logtalk programming language
Table of Contents
Problem Statement
The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.
Implement the Sieve of Eratosthenes algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sieve of Eratosthenes step by step in the Logtalk programming language
Source code in the logtalk programming language
:- object(sieve).
:- public(primes/2).
:- coinductive([
sieve/2, filter/3
]).
% computes a coinductive list with all the primes in the 2..N interval
primes(N, Primes) :-
generate_infinite_list(N, List),
sieve(List, Primes).
% generate a coinductive list with a 2..N repeating patern
generate_infinite_list(N, List) :-
sequence(2, N, List, List).
sequence(Sup, Sup, [Sup| List], List) :-
!.
sequence(Inf, Sup, [Inf| List], Tail) :-
Next is Inf + 1,
sequence(Next, Sup, List, Tail).
sieve([H| T], [H| R]) :-
filter(H, T, F),
sieve(F, R).
filter(H, [K| T], L) :-
( K > H, K mod H =:= 0 ->
% throw away the multiple we found
L = T1
; % we must not throw away the integer used for filtering
% as we must return a filtered coinductive list
L = [K| T1]
),
filter(H, T, T1).
:- end_object.
?- sieve::primes(20, P).
P = [2, 3|_S1], % where
_S1 = [5, 7, 11, 13, 17, 19, 2, 3|_S1] .
You may also check:How to resolve the algorithm Loops/Foreach step by step in the XLISP programming language
You may also check:How to resolve the algorithm Associative array/Iteration step by step in the Jq programming language
You may also check:How to resolve the algorithm Metered concurrency step by step in the Factor programming language
You may also check:How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Ursala programming language
You may also check:How to resolve the algorithm Pangram checker step by step in the ACL2 programming language