+ 3

CHALLENGE : Factorial base conversion

Any number N can be represented by its factorial representation (d0,d1,...dn) where 0<= dn <=n AND N=d0.0!+d1.1!...+dn.n! Write the functions tofactorial(N)=[d0,d1,...dn] AND fromfactorial([d0,d1,...dn]=N Ex: N=463 <=> [0 1 0 1 4 3] because 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0! = 463 Bonus for efficient & readable one liners :)

2nd Nov 2017, 6:07 PM
VcC
VcC - avatar
12 Answers
+ 3
Did somebody say functional programming one-liners? Haskell: x = 463 main = print $ dropWhile (==0) . snd . foldl f (x, []) . reverse . takeWhile (<=x) . scanl1 (*) $ [1..] where f (m, xs) n = (m `mod` n, (m `div` n) : xs) https://tio.run/##LY29CsIwAIT3PsUNDomUYlEcxGyO7g6l0GBSGsxPSULN28ekuBwfx/0sPHyk1jkrszof8eCRd08VYtMkMFyu58ZwZQuuXtmIA4R362tRWoIwdqLoEKwoOjstNGaQ1GIYq@/lJn2QhSL/yH/nztLeeXOre5AjLZND33Ujvov0sg6YFilQ1FNiMBknJth2Z6G2whS3msj5Bw
2nd Nov 2017, 7:19 PM
Schindlabua
Schindlabua - avatar
+ 2
and..heres mine.... both functions are included https://code.sololearn.com/cnk5axwNeK36/?ref=app
2nd Nov 2017, 6:43 PM
sayan chandra
sayan chandra - avatar
+ 2
i am barely breathing now...after doing the code...hurriedly... spare me..fr some time...😊😀😁
2nd Nov 2017, 6:59 PM
sayan chandra
sayan chandra - avatar
+ 2
ok...see now...fact and fromfactorial are one liner functions... 🙋
2nd Nov 2017, 7:02 PM
sayan chandra
sayan chandra - avatar
+ 2
@schindlabua n2fac=lambda n,k=1:[n%k]+n2fac(n//k,k+1) if n else [] if k-1 else [0] in this its not only n%k..its recursive lambda 1st n%k 2ns ( n//k) % (k+1) 3rd (( n//k)//(k+1))%(( k+1)+1) .... going on
3rd Nov 2017, 3:01 PM
sayan chandra
sayan chandra - avatar
0
Haha. What about a functional programming oneliner ?
2nd Nov 2017, 6:58 PM
VcC
VcC - avatar
0
@shindlabua py is the one liner languagz https://code.sololearn.com/cD33vbPPcA9C/?ref=app
2nd Nov 2017, 9:21 PM
VcC
VcC - avatar
0
Wow that's a cool algorithm. Why/how does it work?
3rd Nov 2017, 2:42 AM
Schindlabua
Schindlabua - avatar
0
Nah the other one. Not totally sure why n%k would give you the right answer!
3rd Nov 2017, 2:58 PM
Schindlabua
Schindlabua - avatar
0
I'm an idiot. I read the question wrong and implemented a wrong algorithm that happened to do (almost) the right thing. Sorry for being dense :P
3rd Nov 2017, 3:19 PM
Schindlabua
Schindlabua - avatar
- 1
Define f as fromfact([d0,...dn])=d0.0+d1.1!+...+(i-1)!*((di-1)+f([di,...dn])) then recursively compute f and return f([d0,...dn],1)=fromfact([di,...dn])
3rd Nov 2017, 6:31 AM
VcC
VcC - avatar
- 1
😄😄
3rd Nov 2017, 3:20 PM
sayan chandra
sayan chandra - avatar