Jump to content

Pythagorean triples: Difference between revisions

no edit summary
mNo edit summary
No edit summary
Line 2,452:
<pre>
TRIPLES= 325 PRIMITIVES= 70;
</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<lang PowerShell>
function triples($p) {
if($p -gt 2) {
# ai + bi + ci = pi <= p
# ai < bi < ci --> 3ai < pi <= p and ai + 2bi < pi <= p
1..$p | where{3*$_ -lt $p} | foreach {
$ai = $_
($ai+1)..$p | where{$ai + 2*$_ -lt $p} | foreach{
$bi = $_
($bi+1)..$p | where{
$ci = $_
$pi = $ai + $bi + $ci
($pi -le $p) -and ($ci*$ci -eq $ai*$ai + $bi*$bi)
} |
foreach {
[pscustomobject]@{
a = "$ai"
b = "$bi"
c = "$ci"
p = "$pi"
}
}
}
}
}
else{
"$p must be greater than 2"
}
}
function gcd ($a, $b) {
function pgcd ($n, $m) {
if($n -le $m) {
if($n -eq 0) {$m}
else{pgcd $n ($m-$n)}
}
else {pgcd $m $n}
}
$n = [Math]::Abs($a)
$m = [Math]::Abs($b)
(pgcd $n $m)
}
$triples = (triples 100)
 
$coprime = $triple |
where{((gcd $_.a $_.b) -eq 1) -and ((gcd $_.a $_.c) -eq 1) -and ((gcd $_.b $_.c) -eq 1)}
 
"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100
and $(($coprime).Count) of them are coprime."
</lang>
<b>Output:</b>
<pre>
There are 17 Pythagorean triples with perimeter no larger than 100 and 7 of them are coprime.
</pre>
 
678

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.