How to resolve the algorithm Primality 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 Primality by trial division step by step in the ALGOL W programming language

Table of Contents

Problem Statement

Write a boolean function that tells whether a given integer is prime.

Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed.

Let's start with the solution:

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

Source code in the algol programming language

% returns true if n is prime, false otherwise %
% uses trial division                         %
logical procedure isPrime ( integer value n ) ;
    if n < 3 or not odd( n ) then n = 2
    else begin
        % odd number > 2 %
        integer f, rootN;
        logical havePrime;
        f         := 3;
        rootN     := entier( sqrt( n ) );
        havePrime := true;
        while f <= rootN and havePrime do begin
            havePrime := ( n rem f ) not = 0;
            f         := f + 2
        end;
        havePrime
    end isPrime ;

begin
    logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
    for i := 0 until 32 do if isPrime( i ) then writeon( i_w := 1,s_w := 1, i )
end.

  

You may also check:How to resolve the algorithm Array length step by step in the MiniZinc programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the Maple programming language
You may also check:How to resolve the algorithm String concatenation step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the Slate programming language
You may also check:How to resolve the algorithm Chowla numbers step by step in the Java programming language