Search code examples
algorithmconvertersradix

Converting a number into a special base system


I want to convert a number in base 10 into a special base form like this:

A*2^2 + B*3^1 + C*2^0

A can take on values of [0,1]

B can take on values of [0,1,2]

C can take on values of [0,1]

For example, the number 8 would be

1*2^2 + 1*3 + 1.

It is guaranteed that the given number can be converted to this specialized base system.

I know how to convert from this base system back to base-10, but I do not know how to convert from base-10 to this specialized base system.


Solution

  • In short words, treat every base number (2^2, 3^1, 2^0 in your example) as weight of an item, and the whole number as the capacity of a bag. This problem wants us to find a combination of these items which they fill the bag exactly.

    In the first place this problem is NP-complete. It is identical to the subset sum problem, which can also be seen as a derivative problem of the knapsack problem.

    Despite this fact, this problem can however be solved by a pseudo-polynomial time algorithm using dynamic programming in O(nW) time, which n is the number of bases, and W is the number to decompose. The details can be find in this wikipedia page: http://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming and this SO page: What's it called when I want to choose items to fill container as full as possible - and what algorithm should I use?.