35 lines
895 B
Plaintext
35 lines
895 B
Plaintext
# Declare a function to generate the Stern-Brocot sequence
|
||
func stern_brocot {
|
||
var list = [1, 1]
|
||
{
|
||
list.append(list[0]+list[1], list[1])
|
||
list.shift
|
||
}
|
||
}
|
||
|
||
# Show the first fifteen members of the sequence.
|
||
say 15.of(stern_brocot()).join(' ')
|
||
|
||
# Show the (1-based) index of where the numbers 1-to-10 first appears
|
||
# in the sequence, and where the number 100 first appears in the sequence.
|
||
for i (1..10, 100) {
|
||
var index = 1
|
||
var generator = stern_brocot()
|
||
while (generator() != i) {
|
||
++index
|
||
}
|
||
say "First occurrence of #{i} is at index #{index}"
|
||
}
|
||
|
||
# Check that the greatest common divisor of all the two consecutive
|
||
# members of the series up to the 1000th member, is always one.
|
||
var generator = stern_brocot()
|
||
var (a, b) = (generator(), generator())
|
||
{
|
||
assert_eq(gcd(a, b), 1)
|
||
a = b
|
||
b = generator()
|
||
} * 1000
|
||
|
||
say "All GCD's are 1"
|