Monday 12 August 2013

Pythagorean Triplets


WAP to return the number of Pythagorean triplets a,b,c such that
 a^2 + b^2 = c ^2
 1 < a < b < c <= N.

Solution:


class NumPythagorean {
       public static double e = 1e-30;
public static int numPythagoreanTriplets(int N) {
int x = 0;
for (int c = N; c > 1; c--) {
int sqc = c*c;
for (int b = c-1; b > 1; b--) {
int sqb = b*b;
int sqa = sqc - sqb;
if (sqa > sqb)
                             continue;
 
                         double a = Math.sqrt(sqa);
if ( Math.abs(a - Math.round(a)) < e) {
x++;
}
}
}
return x;
}

public static void main(String[] args) {
int v = numPythagoreanTriplets(100);

System.out.println(v);
       }
}

No comments:

Post a Comment