How to find all pythagorean triples including multiples in processing.js using Euclid's method

163 Views Asked by At

I've been tasked to find the probability of getting a prime number in a Pythagorean triple for a school project, so I tried to code it, but I didn't consider multiples of Pythagorean Triples using Euclid's formula:

(a = m^2 -n^2, b = 2mn, c = m^2 + n^2.).

Ex. 3-4-5 -> 6-8-10.

var primitiveCount = 0;
var m = floor(2), n = floor(1);
var a, b, c;
var ans1, ans2, ans3;


var isPrime = function(value) {
for(var i = 2; i < value; i++) {
    if(value % i === 0) {
        return false;
    }
}
    return value > 1;
};
var j=10;
for(var j = 1; j <= 150; j++){
   primitiveCount = 0;
   m=2;
    n=1;
for(var i=0; i < j; i++) {
  a = ((Math.pow(m,2))-(Math.pow(n,2)));
  b = 2 * n * m;
  c = ((Math.pow(m,2))+(Math.pow(n,2)));
  if(a<b<c) {
  if(Math.pow(a,2) + Math.pow(b,2) === Math.pow(c,2)) {
      ans1 = a;
      ans2 = b;
      ans3 = c;
  }
if(isPrime(ans1) || isPrime(ans2) || isPrime(ans3)){
  println(ans1 + " " + ans2 + " " + ans3 + " ~");
    primitiveCount++;
}else{
  println(ans1 + " " + ans2 + " " + ans3);
}
m++;
n++;
}
}
println(primitiveCount + "/" + j);
}

My code creates unique ones, but does not give me the multiples

1

There are 1 best solutions below

0
On

It is enough to use natural coefficient p

a = p * (m^2 -n^2)
b = p * 2mn
c = p * (m^2 + n^2)

With m>n, m and n coprime and with different parity this method gives all unique triplets.

Conditions together:

p = 1,2,3...
n = 1,2,3...
m = n + 1 + 2 * i, and GCD(m, n) = 1

Seems that your code does not use all values for m, so omits many triplets.

Also use m*m instead of slow pow. Also you don't need to check a^2+b^2=c^2