Pythagorean Triplets in Java

Write a program in Java to generate all the Pythagorean triplets from m to n.

The value of m and n are entered by the user, and m < n.

A Pythagorean triple has three positive integers (a, b, c) such that a2 + b2 = c2.

For example, 32 + 42 = 52

Make sure that the values of m and n are positive.

import java.io.*;
class PythagoreanTriple{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("M = ");
        int m = Math.abs(Integer.parseInt(br.readLine()));
        System.out.print("N = ");
        int n = Math.abs(Integer.parseInt(br.readLine()));
        if(m < n){
            for(int a = m; a <= n; a++){
                for(int b = a + 1; b <= n; b++){
                    for(int c = b + 1; c <= n; c++){
                        if(c * c == a * a + b * b)
                            System.out.println(a + ", " + b + ", " + c);
                    }
                }
            }
        }
    }
}

Leave a Reply

%d bloggers like this: