How to resolve the algorithm Sequence of primes by trial division step by step in the ALGOL W programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sequence of primes by trial division step by step in the ALGOL W programming language

Table of Contents

Problem Statement

Generate a sequence of primes by means of trial division.

Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by other numbers. You may use primes, or any numbers of your choosing, as long as the result is indeed a sequence of primes. The sequence may be bounded (i.e. up to some limit), unbounded, starting from the start (i.e. 2) or above some given value. Organize your function as you wish, in particular, it might resemble a filtering operation, or a sieving operation. If you want to use a ready-made is_prime function, use one from the Primality by trial division page (i.e., add yours there if it isn't there already).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sequence of primes by trial division step by step in the ALGOL W programming language

Source code in the algol programming language

begin
    % use the isPrime procedure from the Primality by Trial Division task     %
    logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
    % sets the elements of p to the first n primes. p must have bounds 1 :: n %
    procedure getPrimes ( integer array p ( * )
                        ; integer value n
                        ) ;
    if n > 0 then begin
        % have room for at least oe prime %
        integer pPos, possiblePrime;
        p( 1 )        := 2;
        pPos          := 2;
        possiblePrime := 3;
        while pPos <= n do begin
            if isPrime( possiblePrime ) then begin
                p( pPos )     := possiblePrime;
                pPos          := pPos + 1;
            end;
            possiblePrime := possiblePrime + 1
        end
    end getPrimes ;

    begin % test getPrimes %
        integer array p( 1 :: 100 );
        getPrimes( p, 100 );
        for i := 1 until 100 do begin
            if i rem 20 = 1 then write(   i_w := 4, s_w := 1, p( i ) )
                            else writeon( i_w := 4, s_w := 1, p( i ) )
        end for_i
    end

end.

  

You may also check:How to resolve the algorithm Letter frequency step by step in the Swift programming language
You may also check:How to resolve the algorithm Colour pinstripe/Display step by step in the Action! programming language
You may also check:How to resolve the algorithm Anonymous recursion step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm URL encoding step by step in the Tcl programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the Plain English programming language