Saturday, February 25, 2017

Pythagorean Triplets Java

Tags

A Pythagorean Triplet is a set of 3 values a, b and c such that the sum of squares of a and b is equal to  square of c.
(a*a) + (b*b)  = (c*c)
Following Program Displays the Pythagorean Triplets upto a user desired value.

import java.util.Scanner;
public class Triplets {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int a, b, c;
        System.out.println("Enter the value of n: ");
        int n = in.nextInt();
        System.out.println("Pythagorean Triplets upto " + n + " are:\n");
        for (a = 1; a <= n; a++) {
            for (b = a; b <= n; b++) {
                for (c = 1; c <= n; c++) {
                    if (a * a + b * b == c * c) {
                        System.out.print(a + ", " + b + ", " + c);
                        System.out.println();
                    }
                   
                    else
                        continue;                  
                }
            }
        }
    }
}