Program to find pythagorean triplets

This program helps you in finding the total number of pythagorean triplets in a given range. Here, the total time complexity, we are taking is O(n^2). In the first loop, we will traverse all the elements from largest to smallest. In the second loop, we will traverse all the remaining elements in the from largest to smallest. Then for each elements we will subtract the square of element found in second loop from the element found in first loop. If the resulting value is a perfect square, then we found a pythagorean triplet, which contains the value of the outer loop, value of inner loop and square root of perfect square.


public class pytho {
    
        public static int numPythagoreanTriplets(int N) {
                int x = 0;
                for (int c = N; c > 1; c--) {
                        int squarec = c*c;
                        for (int b = c-1; b > 1; b--) {
                                int squareb = b*b;
                                int squarea = squarec - squareb;
                                if (squarea > squareb) continue;
                                double a = Math.sqrt(squarea); 
                                if ( Math.abs(a - Math.floor(a)) ==0) {
                                        x++;
                                }
                        }
                }
                return x;
                
        }
        public static void main(String[] args) {
                int v = numPythagoreanTriplets(1000);
                
                System.out.println(v);

        }

}

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++