Re: Factor

Factor: the language, the theory, and the practice.

Reverse Factorial

Saturday, November 26, 2016

#math

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