Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Encoding decimal to factorial and back in JavaScript
The factorial number system uses factorials as bases instead of powers. Each digit position represents a factorial base, where the rightmost digit is base 0!, the next is base 1!, then base 2!, and so on.
How Factorial Encoding Works
In factorial representation, the nth digit from the right can range from 0 to n. For example:
- Position 0 (rightmost): 0 to 0, multiplied by 0! = 1
- Position 1: 0 to 1, multiplied by 1! = 1
- Position 2: 0 to 2, multiplied by 2! = 2
- Position 3: 0 to 3, multiplied by 3! = 6
The decimal number 463 encodes as "341010" because:
463 = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0! 463 = 3×120 + 4×24 + 1×6 + 0×2 + 1×1 + 0×1 463 = 360 + 96 + 6 + 0 + 1 + 0 = 463
Implementation
Here are functions to convert between decimal and factorial representations:
const num = 463;
const decimalToFact = (num = 1) => {
const legend = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
let str = '0';
let i = 2;
while(num) {
str = legend[num % i] + str;
num = Math.floor(num / i);
i++;
}
return str;
};
const factToDecimal = (str = '') => {
const legend = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const l = str.length;
return str
.split('')
.reduce((acc, digit, i) => Number(acc) * (l - i) + legend.indexOf(digit), 0);
};
const fact = decimalToFact(num);
const dec = factToDecimal(fact);
console.log(`Decimal ${num} to factorial: ${fact}`);
console.log(`Factorial ${fact} to decimal: ${dec}`);
Decimal 463 to factorial: 341010 Factorial 341010 to decimal: 463
How the Algorithm Works
Decimal to Factorial: We repeatedly divide by increasing factorials (2!, 3!, 4!...) and collect remainders. The remainders form our factorial digits from right to left.
Factorial to Decimal: We multiply each digit by its corresponding factorial and sum the results using the reduce function with positional weighting.
Testing with More Examples
// Test additional numbers
const testNumbers = [10, 25, 100];
testNumbers.forEach(n => {
const factorial = decimalToFact(n);
const backToDecimal = factToDecimal(factorial);
console.log(`${n} -> ${factorial} -> ${backToDecimal}`);
});
10 -> 1210 25 -> 10110 100 -> 40120
Conclusion
The factorial number system provides a unique way to represent integers using factorial bases. This encoding is particularly useful in combinatorics and permutation algorithms where factorial relationships are natural.
