This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,6 @@
proc ifact n {
for {set i $n; set sum 1} {$i >= 2} {incr i -1} {
set sum [expr {$sum * $i}]
}
return $sum
}

View file

@ -0,0 +1,3 @@
proc rfact n {
expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]}
}

View file

@ -0,0 +1 @@
proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}}

View file

@ -0,0 +1,17 @@
proc ifact_caching n {
global fact_cache
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
}

View file

@ -0,0 +1,11 @@
puts [ifact 30]
puts [rfact 30]
puts [ifact_caching 30]
set n 400
set iterations 10000
puts "calculate $n factorial $iterations times"
puts "ifact: [time {ifact $n} $iterations]"
puts "rfact: [time {rfact $n} $iterations]"
# for the caching proc, reset the cache between each iteration so as not to skew the results
puts "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]"

View file

@ -0,0 +1,5 @@
package require math::special
proc gfact n {
expr {round([::math::special::Gamma [expr {$n+1}]])}
}