The Factorial Number System, also called factoradic, is a mixed radix numeral system. The factorials determine the place value of a number.
In this system, the right most digit can be either 0 or 1, the second rightmost digit can be 0, 1 or 2, and so on. This means that an n
digit factoradic number can have a maximum value of (n + 1)!
.
For example, to convert the factoradic number 24201
to decimal you would do this:
2 * 5! = 240
4 * 4! = 96
2 * 3! = 12
0 * 2! = 0
1 * 1! = 1
240 + 96 + 12 + 0 + 1 = 349
Hence the factoradic number 24201
is 349
base 10
.
To convert a decimal number (with 349
as an example) into a factoradic number, you would do this:
Take the largest factorial less than the number. In this case it is 120
, or 5!
.
349 / 5! = 2 r 109
109 / 4! = 4 r 13
13 / 3! = 2 r 1
1 / 2! = 0 r 1
1 / 1! = 1 r 0
Hence 349
base 10
is the factoradic number 24201
.
Your challenge is to create the shortest program or function that converts an input number to the other base.
The input will be a string representation of a non-negative integer. A factoradic number will be preceded by a !
(eg. !24201
), while a decimal number will not be preceded by anything. You may assume that the maximum input will be 10! - 1
- 3628799
in decimal and 987654321
in factoradic. This means that letters will not appear in a factoradic input/output.
The program doesn't need to prepend a !
to a factoradic output, and may output a string or an integer. The input may be in any reasonable format.
Test cases:
Input: 1234
Output: 141120
Input: 746
Output: 101010
Input: !54321
Output: 719
Input: !30311
Output: 381