#!/usr/bin/ruby
# 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.
1..15 -> map(stern_brocot()).join(' ').say;
# 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.
[(1..10)..., 100].each { |i|
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(Math.gcd(a, b), 1);
a = b;
b = generator();
} * 1000;
say "All GCD's are 1";