Sieve of Eratosthenes: Difference between revisions
Content deleted Content added
imported>Polarit new elm version |
imported>Polarit →{{header|Elm with immutable arrays}}: fixed header |
||
Line 6,647: | Line 6,647: | ||
Found 78498 primes to 1000000 in 192 milliseconds.</pre> |
Found 78498 primes to 1000000 in 192 milliseconds.</pre> |
||
== |
===Elm with immutable arrays=== |
||
<syntaxhighlight lang="elm"> |
<syntaxhighlight lang="elm"> |
||
module PrimeArray exposing (main) |
module PrimeArray exposing (main) |
||
Line 6,654: | Line 6,654: | ||
import Html exposing (div, h1, p, text) |
import Html exposing (div, h1, p, text) |
||
import Html.Attributes exposing (style) |
import Html.Attributes exposing (style) |
||
{- |
{- |
||
The Eratosthenes sieve task in Rosetta Code does not |
The Eratosthenes sieve task in Rosetta Code does not accept |
||
the use of modulo function (modBy |
the use of modulo function (allthough Elm functions modBy and remainderBy work always correctly as they require type Int excluding type Float). |
||
Thus the |
Thus the solution needs an indexed work array |
||
as Elm has no indexes for lists. |
as Elm has no indexes for lists. |
||
In this method we need no division remainder calculations, |
In this method we need no division remainder calculations, |
||
Line 6,666: | Line 6,665: | ||
We need the indexes that we know, where the marking of the non-primes |
We need the indexes that we know, where the marking of the non-primes |
||
shall be set. |
shall be set. |
||
Because everything is immutable in Elm, every change of array values will create a new array save the original array unchanged. That makes the program running slower or consuming more space of memory than with non-functional imperative languages. All conventional loops (for, while, until) are excluded in Elm because immutability requirement. |
|||
Live: https://ellie-app.com/pTHJyqXcHtpa1 |
Live: https://ellie-app.com/pTHJyqXcHtpa1 |
||
Line 6,722: | Line 6,722: | ||
{- As Elm has no loops (for, while, until) |
|||
we must use recursion instead! |
|||
The search of prime starts allways saving the |
|||
first found value (not setting zero) and continues setting the multiples of prime to zero. |
|||
Zero is no integer and may thus be used as marking of non-prime numbers. At the end, only the primes remain in the array and the zeroes are removed from the resulted array to be shown in Html. |
|||
-- the first location of the found prime as the later found values are |
|||
-} |
|||
-- multiples and set zero |
|||
⚫ | |||
⚫ | |||
loopI : Int -> Int -> Array Int -> Array Int |
loopI : Int -> Int -> Array Int -> Array Int |
||
Line 6,818: | Line 6,818: | ||
Found 35 primes |
Found 35 primes |
||
</pre> |
</pre> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |