Yellowstone sequence: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: %v -> %V)
Line 1,197: Line 1,197:
<pre>First 30 values in the yellowstone sequence:
<pre>First 30 values in the yellowstone sequence:
[1, 2, 3, 4, 9, 8, 15, 14, 5, 6, 25, 12, 35, 16, 7, 10, 21, 20, 27, 22, 39, 11, 13, 33, 26, 45, 28, 51, 32, 17]</pre>
[1, 2, 3, 4, 9, 8, 15, 14, 5, 6, 25, 12, 35, 16, 7, 10, 21, 20, 27, 22, 39, 11, 13, 33, 26, 45, 28, 51, 32, 17]</pre>

=={{header|Nim}}==
===Procedure version===
This version uses a set and, so, is limited to 65536 elements. It is easy to change this limit by using a HashSet (standard module “sets”) instead of a set. See the iterator version which uses such a HashSet.
<lang Nim>import math

proc yellowstone(n: int): seq[int] =
assert n >= 3
result = @[1, 2, 3]
var present = {1, 2, 3}
var start = 4
while result.len < n:
var candidate = start
while true:
if candidate notin present and gcd(candidate, result[^1]) == 1 and gcd(candidate, result[^2]) != 1:
result.add candidate
present.incl candidate
while start in present: inc start
break
inc candidate

echo yellowstone(30)</lang>
{{out}}
<pre>@[1, 2, 3, 4, 9, 8, 15, 14, 5, 6, 25, 12, 35, 16, 7, 10, 21, 20, 27, 22, 39, 11, 13, 33, 26, 45, 28, 51, 32, 17]</pre>

===Iterator version===
This version uses a HashSet, but using a set as in the previous version is possible if we accept the limit of 65536 elements.
<lang Nim>import math, sets

iterator yellowstone(n: int): int =
assert n >= 3
for i in 1..3: yield i
var present = [1, 2, 3].toHashSet
var prevLast = 2
var last = 3
var start = 4
for _ in 4..n:
var candidate = start
while true:
if candidate notin present and gcd(candidate, last) == 1 and gcd(candidate, prevLast) != 1:
yield candidate
present.incl candidate
prevLast = last
last = candidate
while start in present: inc start
break
inc candidate

for n in yellowstone(30):
stdout.write " ", n
echo()</lang>
{{out}}
<pre> 1 2 3 4 9 8 15 14 5 6 25 12 35 16 7 10 21 20 27 22 39 11 13 33 26 45 28 51 32 17</pre>


=={{header|Perl}}==
=={{header|Perl}}==