Tuesday, February 2, 2021

Does given array contains a triplet (a^2 + b^2 = c^2) ?

 





package com.company;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TripletFounder {
public static void main(String[] args) {
Integer[] array = {3, 1, 4, 6, 5};
double pow = (int) Math.pow(2, array.length);
for (int i = 0; i < pow; i++) {
List<Integer> subsSeqWithSize3 = new ArrayList<>();
for (int j = 0; j < array.length; j++) {
if (BigInteger.valueOf(i).testBit(j)) {
System.out.print(array[j] + " ");
subsSeqWithSize3.add(array[j]);
}
}
if (subsSeqWithSize3.size() == 3) {
Collections.sort(subsSeqWithSize3);
if (Math.pow(subsSeqWithSize3.get(0), 2) + Math.pow(subsSeqWithSize3.get(1), 2) == Math.pow(subsSeqWithSize3.get(2), 2)) {
System.out.println("Found triplet = " + subsSeqWithSize3.toString());
System.exit(0);
}
}
System.out.println("");
}
}
}