(05-01-2019 05:05 PM)Giuseppe Donnini Wrote: Here's another solution:
Considering that n!! is equivalent to n·(n-2)·(n-4)· ... ·1 for every positive integer n ≠ 0 (odd or even), all it needs is a simple loop which calculates the next factor and multiplies it with the running product. Such a solution could do entirely without local variables and algebraic objects, requiring only stack manipulations, and very few in number:
1 @ Initialize result.
SWAP 2 @ Loop down from n to 2.
FOR f f * @ Multiply with current factor.
-2 STEP @ Decrement factor by 2 ; repeat until factor < 2.
Taking into account the special case where n = 0 , we finally have:
Code:
@ NAME : DF (Double factorial)
@ STACK : ( n --> n!! )
\<<
1 @ Initialize result.
IF SWAP DUP 0 == @ If n = 0,
THEN DROP @ then n!! = 1 (just drop n, 1 already on stack).
ELSE 2 @ Otherwise: Loop down from n to 2.
FOR f f * @ Multiply with current factor.
-2 STEP @ Decrement factor by 2 ; repeat until factor < 2.
\>>
Hi Giuseppe,
Thank you, very interesting and nice solution. I tested it (END added). Works fine, but if I use very large numbers, the program runs in an infinite loop. The other programs output the message "Integer too large". But I can easily query this.
Kind regards
Joerg