# Encoding decimal to factorial and back in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

Coding decimal numbers with factorials is a way of writing out numbers in a base system that depends on factorials, rather than powers of numbers.

In this system, the last digit is always 0 and is in base 0!. The digit before that is either 0 or 1 and is in base 1!. The digit before that is either 0, 1, or 2 and is in base 2!, etc. More generally, the nth-to-last digit is always 0, 1, 2, ..., n and is in base n!.

We will need two functions. The first one will receive a decimal number and return a string with the factorial representation.

The second one will receive a string with a factorial representation and produce the decimal representation.

For instance −

The decimal number 463 is encoded as "341010", because −

463 = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0!

## Example

Following is the code −

Live Demo

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((a,e,i) => Number(a) * (l - i) + legend.indexOf(e), 0);
};
const fact = decimalToFact(num);
const dec = factToDecimal(fact);
console.log(fact);
console.log(dec);

## Output

Following is the console output −

341010
463
Published on 19-Apr-2021 08:03:24