greedy_egyptian_fractions.sf 499 B

1234567891011121314151617181920212223
  1. #!/usr/bin/ruby
  2. # Greedy algorithm for Egyptian fractions
  3. # See also:
  4. # https://oeis.org/A001466
  5. # https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions
  6. func egyptian_denominators(r, count=8) {
  7. gather {
  8. count.times {
  9. r -= 1/take(ceil(1/r))
  10. }
  11. }
  12. }
  13. say egyptian_denominators(Num.pi)
  14. say egyptian_denominators(Num.pi).sum { 1/_ }
  15. __END__
  16. [1, 1, 1, 8, 61, 5020, 128541455, 162924332716605980]
  17. 3.14159265358979323846264338327950284945450236218