stern-brocot_sequence.sf 946 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/ruby
  2. # Declare a function to generate the Stern-Brocot sequence
  3. func stern_brocot {
  4. var list = [1, 1];
  5. {
  6. list.append(list[0]+list[1], list[1]);
  7. list.shift;
  8. }
  9. }
  10. # Show the first fifteen members of the sequence.
  11. 1..15 -> map(stern_brocot()).join(' ').say;
  12. # Show the (1-based) index of where the numbers 1-to-10 first appears
  13. # in the sequence, and where the number 100 first appears in the sequence.
  14. [(1..10)..., 100].each { |i|
  15. var index = 1;
  16. var generator = stern_brocot();
  17. while (generator() != i) {
  18. ++index;
  19. }
  20. say "First occurrence of #{i} is at index #{index}";
  21. }
  22. # Check that the greatest common divisor of all the two consecutive
  23. # members of the series up to the 1000th member, is always one.
  24. var generator = stern_brocot();
  25. var (a, b) = (generator(), generator());
  26. {
  27. assert_eq(Math.gcd(a, b), 1);
  28. a = b;
  29. b = generator();
  30. } * 1000;
  31. say "All GCD's are 1";