Hey try to fix this one:
DEF FAC(V1)
VAR RET
FOR I=V1 TO 1 STEP -1
RET=RET*I
NEXT
RETURN RET
END
The problem is that it isn't fast enough:
DEF FAC(V1)
VAR RET=MAX(V1,1)
FOR I=V1-1 TO 2 STEP -1
RET=RET*I
NEXT
RETURN RET
END
This drops like, 2 redundant iterations.
Except that the factorial of any inputs > 12 won't even fit in an int32 (and is defined only for nonnegative integers), so we can implement it as a lookup table with little space overhead instead.
@SEQ_FACT
DATA 1,1,2,6,24,120,720,5040,40320,362880,3628800,479001600
DIM FACT_TBL[0]
COPY FACT_TBL,@SEQ_FACT
DEF FASTFACT(N)
IF N>=0 && N<12 THEN RETURN FACT_TBL[N]
RETURN 0
END
Behavior for unsafe inputs isn't well defined, so you might want to
STOP instead of returning -1 or 0 or something...
FACT_TBL[n] can be indexed directly when you don't even need the safety check.