How to resolve the algorithm Sieve of Eratosthenes step by step in the Scilab programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sieve of Eratosthenes step by step in the Scilab 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 Scilab programming language

Source code in the scilab programming language

function a = sieve(n)
    a = ~zeros(n, 1)
    a(1) = %f
    for i = 1:n
        if a(i)
            j = i*i
            if j > n
                return
            end
            a(j:i:n) = %f
        end
    end
endfunction

find(sieve(100))
// [2 3 5 ... 97]

sum(sieve(1000))
// 168, the number of primes below 1000

  

You may also check:How to resolve the algorithm Globally replace text in several files step by step in the Mathematica / Wolfram Language programming language
You may also check:How to resolve the algorithm Primality by trial division step by step in the Scheme programming language
You may also check:How to resolve the algorithm Minimum multiple of m where digital sum equals m step by step in the FOCAL programming language
You may also check:How to resolve the algorithm Loops/N plus one half step by step in the bc programming language
You may also check:How to resolve the algorithm Operator precedence step by step in the VBScript programming language