nth_molecular_number.rb 991 B

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/ruby
  2. # Generate the n-th molecular number that is the product of a subset of primes given.
  3. # For primes = [2,3,5], the n-th molecular number is the n-th 5-smooth number.
  4. # See also:
  5. # https://en.wikipedia.org/wiki/Regular_number
  6. # https://en.wikipedia.org/wiki/Smooth_number
  7. def molecule_generator(atoms)
  8. s = []
  9. atoms.size.times { s << [1] }
  10. lambda {
  11. n = s.map {|t| t[0] }.min
  12. atoms.size.times { |i|
  13. s[i] = [] unless s[i]
  14. s[i].shift if (s[i][0] == n)
  15. s[i] << (n * atoms[i])
  16. }
  17. return n
  18. }
  19. end
  20. def nth_molecular_number(n, atoms)
  21. g = molecule_generator(atoms)
  22. (n-1).times { g.call }
  23. g.call
  24. end
  25. puts nth_molecular_number(12, [2,7,13,19])
  26. puts nth_molecular_number(25, [2,5,7,11,13,23,29,31,53,67,71,73,79,89,97,107,113,127,131,137])
  27. puts nth_molecular_number(100000, [7,19,29,37,41,47,53,59,61,79,83,89,101,103,109,127,131,137,139,157,167,179,181,199,211,229,233,239,241,251])