A few years ago, I wrote about implementing various factorials using Factor. Recently, I came across a programming challenge to implement a "reverse factorial" function to determine what factorial produces a number, or none if it is not a factorial.
To do this, we examine each factorial in order, checking against the number being tested:
: reverse-factorial ( m -- n ) 1 1 [ 2over > ] [ 1 + [ * ] keep ] while [ = ] dip and ;
And some unit tests:
{ 10 } [ 3628800 reverse-factorial ] unit-test { 12 } [ 479001600 reverse-factorial ] unit-test { 3 } [ 6 reverse-factorial ] unit-test { f } [ 18 reverse-factorial ] unit-test
I wonder if it's possible to get the inverse package to compute the reverse of a factorial somehow.
ReplyDeleteThis should do it:
ReplyDeletehttps://github.com/factor/factor/commit/8bdaf26d6b0e02a2b43e6adc493f5b8950b36413