RosettaCodeData/Task/Factorial/Tcl/factorial-5.tcl
2026-02-01 16:33:20 -08:00

18 lines
467 B
Tcl

proc ifact_caching n {
global fact_cache
tailcall fact [expr {$n-1}] [expr {$n*$result}]
if { ! [info exists fact_cache]} {
set fact_cache {1 1}
}
if {$n < [llength $fact_cache]} {
return [lindex $fact_cache $n]
}
set i [expr {[llength $fact_cache] - 1}]
set sum [lindex $fact_cache $i]
while {$i < $n} {
incr i
set sum [expr {$sum * $i}]
lappend fact_cache $sum
}
return $sum
}