Search code examples
javaalgorithmhamming-numbers

Print a list, in ascending order and with no duplicate, of positive integers that have no prime factor other than 2, 3, or 5


This is a programming question on my homework for one of my courses. I haven't programmed in a couple years and I wasn't that great to begin with. I'm currently going through tutorials to get back up to speed, but it will take some time. If you guys can help me out with this problem, I would really appreciate it.

Constraints:

Each term of this sequence is a positive integer of the form 2^i*3^j*5^k, for all non-negative integers i, j, and k with i + j + k >= 1.

Can't use arrays. The algorithm to solving this problem must involve the repeated creation and merger of lists. Specifically 5 lists; a final list, temp list, and three term lists.

"The final list grows by being merged with the current temp list. The temp list, in turn, is replaced by the merger of the three term lists. New term lists are generated by multiplying the new temp list by 2, 3, and 5 respectively"

The desired sequence would go as follows: 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, . . .


Solution

  • As you've explained in your question, you might do your algorithm recursively.

    At step n:

    The final list will represent the set F(n) = {m | m = 2^i*3^j*5^k, 1<=i+j+k<=n}

    The temp list will represent the set T(n) = {m | m = 2^i*3^j*5^k, i+j+k=n}

    Then, the "L2" term list will be L2(n) = 2*T(n-1)

    the "L3" term list will be L3(n) = 3*T(n-1)

    the "L5" term list will be L5(n) = 5*T(n-1)

    To get T, T(n) = merge(L2(n), L3(n), L5(n))

    To get F, F(n) = merge(F(n-1), T(n))

    Once you've got this, you have to implement a function to merge 2 lists. In the main function, you just have to translate these in Java.

    You can also make the lists always sorted so that merge is easy and efficient! In java, I think you can use LinkedList or ArrayList, both work fine.

    After all, it's your homework.