fork download
  1. object Main extends App {
  2. // from stackoverflow.com/a/54623726/849891
  3.  
  4. def hamming(n: Int): Seq[BigInt] = {
  5. def next(x: Int, factor: Int, v: BigInt): BigInt = {
  6. Iterator.from(x).map(BigInt(_)).dropWhile(factor * _ <= v).take(1).next()
  7. }
  8.  
  9. Iterator.iterate((1, 1, 1, BigInt(1), 1)) { case (i, j, k, v, count) =>
  10. val a = next(i, 2, v)
  11. val b = next(j, 3, v)
  12. val c = next(k, 5, v)
  13. val m = Seq(2 * a, 3 * b, 5 * c).min
  14.  
  15. (a.intValue(), b.intValue(), c.intValue(), m, count + 1)
  16. }
  17. .takeWhile(_._5 <= n)
  18. .map(_._4)
  19. .toSeq
  20. }
  21.  
  22. val list = List() ++ hamming(100)
  23. println(list.take(20))
  24. }
Success #stdin #stdout 0.6s 2181632KB
stdin
Standard input is empty
stdout
List(1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26)