0

Hamming numbers are numbers of the form 2^a3^b5^c. If I want to generate the nth Hamming number, one way to do this is to use a min-heap and a hashset as in the following pseudo-code:

heap = [1]
seen = hashset()
answer = []

while len(answer) < n:
    x = heap.pop()
    answer.append(x)
    for f in [2,3,5]:
        if f*x not in seen:
            heap.push(f*x)
            seen.add(f*x)
return answer[-1]

I think this is O(n log n) in time complexity: each time we run the block of code in the while loop, we do one pop and up to three pushes, each of which is logarithmic in the size of the heap, and the size of the heap is at worse linear in the number of times we've performed the while loop.

Questions:

  1. Is my timing analysis correct?
  2. Is there an algorithm which can do this faster, i.e. linear time complexity in n? What is the best-case for time complexity for this problem?
Hank Scorpio
  • 101
  • 1
  • Yes, the complexity is correct. You can find implementations in many languages [here](https://rosettacode.org/wiki/Hamming_numbers#Determination_of_the_nth_Hamming_number_by_processing_of_error_band). [This post](https://stackoverflow.com/questions/46893239/hamming-numbers-by-intervals) probably answers your question about better algorithms too. – Jérôme Richard Jan 12 '22 at 00:13
  • [Another similar question](https://stackoverflow.com/questions/57596718/ugly-number-mathematical-intuition-for-dp). – user3386109 Jan 12 '22 at 01:30

0 Answers0