The sieve of Sundaram: Difference between revisions
m
→{{header|AppleScript}}: Yet another optimisation and attendant comment work.
m (→{{header|AppleScript}}: Optimisation better explained in the comments.) |
m (→{{header|AppleScript}}: Yet another optimisation and attendant comment work.) |
||
Line 86:
=={{header|AppleScript}}==
The "nth prime" calculation here's gleaned from the Python and Julia solutions and the limitations to marking partly from the Phix.
<lang applescript>on sieveOfSundaram(indexRange)
if (indexRange's class is list) then
Line 99 ⟶ 101:
end script
set {unmarked, marked} to {true, false}
--
-- 1-based indices. The Python and Julia solutions note that the nth prime is approximately
-- n * 1.2 * log(n), but the number from which it'll be
-- 15 is added too here to ensure headroom
set limit to (do shell script "echo '" & n2 & " * 0.6 * l(" & n2 & ") + 15'| bc -l") as integer
set len to 1500
Line 115 ⟶ 116:
end repeat
-- Since it's a given that every third slot from 4 on will be "marked" (changed to false), there'll be
-- no need to check these and thus no point in actually marking them! Skip the step = 3 marking sweep
-- and the first slot of every three for marking in the subsequent sweeps.
-- Like the Phix solution, mark only from half the square of the step size, but adjusted
-- to sync the repeat to the second slot in each group of three for marking.
repeat with j from (step * step div 2 - (step * 2 mod 3) * step + step) to (limit - step) by (step * 3)
set item j of o's lst to marked▼
set item (j + step) of o's lst to marked▼
end repeat▼
end repeat
-- Calculate the primes from the indices of the unmarked slots
-- and store them in the list from the beginning.
set i to 1
set item i of o's lst to
repeat with n from 2 to limit by 3
if (item n of o's lst) then
set i to i + 1
set item i of o's lst to
end if
if (item (n + 1) of o's lst) then
set i to i + 1
set item i of o's lst to n
if (i = n2) then exit repeat
end if
▲ if (i ≥ n2) then exit repeat -- Enough primes obtained.
▲ repeat with j from (n + 2 + step) to (limit - step) by step * 3
▲ set item j of o's lst to marked
▲ set item (j + step) of o's lst to marked
▲ end repeat
end repeat
-- set beginning of o's lst to 2 -- Uncomment if required.
Line 144 ⟶ 149:
end sieveOfSundaram
-- Task code:
on join(lst, delim)
set astid to AppleScript's text item delimiters
Line 168 ⟶ 174:
end task
task()></lang>
{{output}}
|