Pythagorean triples: Difference between revisions

m
→‎{{header|Tcl}}: Remove coroutines (and version restriction); not needed any more
m (→‎{{header|Tcl}}: Smarter still by avoiding recursion; queue is not culled during generation, _much_ slower to do that)
m (→‎{{header|Tcl}}: Remove coroutines (and version restriction); not needed any more)
Line 883:
=={{header|Tcl}}==
Using the efficient method based off the Wikipedia article:
<lang tcl>proc countPythagoreanTriples n{limit} {
{{works with|Tcl|8.6}}
<lang tcl>package require Tcl 8.6
proc gentrips {limit} {
lappend q 3 4 5
set idx [set count [set prim 0]]
while {$idx < [llength $q]} {
set a [lindex $q $idx]
Line 894 ⟶ 892:
incr idx
if {$a + $b + $c <= $limit} {
incr prim
yield [list 1 1 $a $b $c]
for {set i 21} {$i*$a+$i*$b+$i*$c <= $limit} {incr i} {
incr count
yield [list 1 0 [expr {$a*$i}] [expr {$b*$i}] [expr {$c*$i}]]
}
lappend q \
Line 904 ⟶ 902:
}
}
return 0[list $count $prim]
}
proc countPythagoreanTriples n {
set count [set primitive 0]
coroutine p eval "yield;gentrips $n"
while {[lassign [p] more p a b c;set more]} {
incr count
incr primitive $p
}
list $count $primitive
}
for {set i 10} {$i <= 10000000} {set i [expr {$i*10}]} {
lassign [countPyTripcountPythagoreanTriples $i] count primitive
puts "perimeter limit $i => $count triples, $primitive primitive"
}</lang>
Anonymous user