How to resolve the algorithm Sieve of Eratosthenes step by step in the J programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sieve of Eratosthenes step by step in the J 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 J programming language
Source code in the j programming language
sieve=: {{
r=. 0#t=. y# j=.1
while. y>j=.j+1 do.
if. j{t do.
t=. t > y$j{.1
r=. r, j
end.
end.
}}
sieve 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve=: {{
r=. 0#t=. y# j=.1
while. y>j=.j+1 do.
if. j{t do.
echo j;(y$j{.1);t=. t > y$j{.1
r=. r, j
end.
end.
}}
sieve 10
┌─┬───────────────────┬───────────────────┐
│2│1 0 1 0 1 0 1 0 1 0│0 1 0 1 0 1 0 1 0 1│
└─┴───────────────────┴───────────────────┘
┌─┬───────────────────┬───────────────────┐
│3│1 0 0 1 0 0 1 0 0 1│0 1 0 0 0 1 0 1 0 0│
└─┴───────────────────┴───────────────────┘
┌─┬───────────────────┬───────────────────┐
│5│1 0 0 0 0 1 0 0 0 0│0 1 0 0 0 0 0 1 0 0│
└─┴───────────────────┴───────────────────┘
┌─┬───────────────────┬───────────────────┐
│7│1 0 0 0 0 0 0 1 0 0│0 1 0 0 0 0 0 0 0 0│
└─┴───────────────────┴───────────────────┘
2 3 5 7
You may also check:How to resolve the algorithm Leap year step by step in the MUMPS programming language
You may also check:How to resolve the algorithm Literals/Integer step by step in the Logo programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the Ceylon programming language
You may also check:How to resolve the algorithm Parallel calculations step by step in the Java programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the SparForte programming language