Given a positive integer, print that many hamming numbers, in order.


  • Input will be a positive integer \$n \le 1,000,000 \$
  • Output should be the first n terms of https://oeis.org/A051037
  • Execution time must be < 1 minute
  • This is ; shortest code wins
  • 2
    \$\begingroup\$ Which aim an answer should have? Golf? Most effective algorithm? Just searching of solution methods? \$\endgroup\$ – Nakilon Jan 28 '11 at 0:19
  • \$\begingroup\$ Sorry for not being specific. I haven't solved this myself, so I'm not sure if the bounds I put in are reasonable. Please let me know. \$\endgroup\$ – grokus Jan 30 '11 at 22:54
  • \$\begingroup\$ OEIS \$\endgroup\$ – Stephen Aug 18 '17 at 17:24
  • 3
    \$\begingroup\$ 1 is a Hamming number, so, printing 1,000,000 1s is conformant with your specs. It will also be in order, i.e. not an unordered sequence. :) \$\endgroup\$ – Will Ness Jan 5 '18 at 15:03

Haskell, 101 97 92+|n| characters

h=1:m 2h&m 3h&m 5h
main=print$take 1000000h

Computes the full million in 3.7s on the machine I tested on (variably more if you actually want the output stored)


-- print out the first million Hamming numbers
main = print $ take 1000000 h

-- h is the entire Hamming sequence.
-- It starts with 1; for each number in the
-- sequence, 2n, 3n and 5n are also in.
h = 1 : (m 2 h) & (m 3 h) & (m 5 h)

-- helper: m scales a list by a constant factor
m f xs = map (f*) xs

-- helper: (&) merges two ordered sequences
a@(ha:ta) & b@(hb:tb)
    |    ha < hb = ha : ta & b
    |    ha > hb = hb :  a & tb
    |  otherwise = ha : ta & tb

All Haskell is notoriously good at: defining a list as a lazy function of itself, in a way that actually works.

  • 1
    \$\begingroup\$ You don't get the positive integer parameter, that add more size to your code \$\endgroup\$ – Zhen Aug 24 '11 at 8:23
  • \$\begingroup\$ @Zhen The positive integer parameter is the second-to-last token, and its size is declared outfront in the header. \$\endgroup\$ – J B Aug 24 '11 at 8:30

Python 181 Characters

while n:
    print h[-1]
    while h[i]*2<=h[-1]:
    while h[j]*3<=h[-1]:
    while h[k]*5<=h[-1]:
  • \$\begingroup\$ How is this 181 chars? I've saved this to a file, removing the whitespace after h=[], using a minimum tab distance, and single character line breaks, and the file size ends up being 187 bytes. \$\endgroup\$ – nitro2k01 Dec 31 '13 at 16:50
  • 1
    \$\begingroup\$ Anyway... Trivial optimization: h=[1]. Also, give a number directly in the source code, to save characters for numbers <1000000. \$\endgroup\$ – nitro2k01 Dec 31 '13 at 17:13
  • \$\begingroup\$ And oops, sorry, didn't realize the answer is super-old. \$\endgroup\$ – nitro2k01 Dec 31 '13 at 17:15
  • \$\begingroup\$ @nitro2k01, I make it 183 chars. (There's some trailing whitespace at the end of the first line, and the indentation should be a space for one level and a tab for two levels). \$\endgroup\$ – Peter Taylor Jan 1 '14 at 10:33

APL (Dyalog Classic), 34 23 bytes


Try it online!

TIO throws a WS FULL error for \$n = 1000000\$, but Dyalog on my laptop runs in about 45 seconds, not counting the scrolling to display numbers.

{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}⍣≡∘1     Monadic function:
{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}         Define the following helper function g(⍺,⍵):
             ⍵∘.×⍳5             Make a multiplication table between ⍵ and (1 2 3 4 5).
                                (Including 4 is unnecessary but saves bytes.)
            ,                   Flatten the table into an array.
           ∪                    Keep unique elements.
    {⍵[⍋⍵]}                     Grade up the array and access it at those indices.
                                (This is the APL idiom to sort an array.)
 ⍺⍴                             Keep the first ⍺ elements; pad by repeating the array.
{⍺⍴{⍵[⍋⍵]}∪,⍵∘.×⍳5}⍣≡       Repeatedly apply g with some fixed left argument
                             until a fixed point is reached.
                             At this point we have a dyadic function that takes
                             n on the left and the starting value on the right,
                             and returns multiples of the n Hamming numbers.
                      ∘1     Fix 1 as the right argument.

Ruby - 154 231 characters

def k i,n;(l=Math).log(i,2)*l.log(i,3)*l.log(i,5)/6>n end
def l i,n;k(i,n)?[i]:[i]+l(5*i,n)end
def j i,n;k(i,n)?[i]:[i]+j(3*i,n)+l(5*i,n)end
def h i,n;k(i,n)?[i]:[i]+h(2*i,n)+j(3*i,n)+l(5*i,n)end
puts h(1,n=gets.to_i).sort.first n

And now it's fast enough, there is definitely a lot of golfing that can still happen though.

→ time echo 1000000 | ruby golf-hamming.rb | wc
1000000 1000000 64103205
echo 1000000  0.00s user 0.00s system 0% cpu 0.003 total
ruby golf-hamming.rb  40.39s user 0.81s system 99% cpu 41.229 total
wc  1.58s user 0.05s system 3% cpu 41.228 total

Haskell, 71

h n = drop n $ iterate (\(_,(a:t))-> (a,union t [2*a,3*a,5*a])) (0,[1])


*Main> map fst $ take 20 $ h 1
  • \$\begingroup\$ The spec calls for you to print, so the code to print should be counted. This also allows a fair comparison against the other Haskell implementation. \$\endgroup\$ – Peter Taylor Jan 1 '14 at 10:28
  • \$\begingroup\$ @PeterTaylor How many characters do you think I should add? \$\endgroup\$ – Timtech Jan 1 '14 at 14:59

Ursala, 103

#import std
#import nat
smooth"p" "n" = ~&z take/"n" nleq-< (rep(length "n") ^Ts/~& product*K0/"p") <1>

Output for main = smooth<2,3,5>* nrange(1,20)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.