How to resolve the algorithm Sieve of Eratosthenes step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sieve of Eratosthenes step by step in the Wren 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 Wren programming language
Source code in the wren programming language
var sieveOfE = Fn.new { |n|
if (n < 2) return []
var comp = List.filled(n-1, false)
var p = 2
while (true) {
var p2 = p * p
if (p2 > n) break
var i = p2
while (i <= n) {
comp[i-2] = true
i = i + p
}
while (true) {
p = p + 1
if (!comp[p-2]) break
}
}
var primes = []
for (i in 0..n-2) {
if (!comp[i]) primes.add(i+2)
}
return primes
}
System.print(sieveOfE.call(100))
You may also check:How to resolve the algorithm Bulls and cows step by step in the Clojure programming language
You may also check:How to resolve the algorithm Permutations by swapping step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Input loop step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Create a file step by step in the Fortran programming language
You may also check:How to resolve the algorithm Repeat step by step in the Red programming language