Sunday, 25 November 2012

Finding Pythagorean triplets in an array.



//   WORKING code in java with  time O(n^2)

import java.util.Arrays;
public class PythagoreanTripletsInArray {
public static double [] getSquare(String [] args){
double [] array = new double[args.length];
for(int i=0;i<args.length;i++){
double j=Integer.parseInt(args[i]);
array[i]=j*j;
}
return array;
}
public static void main(String [] args ){
double [] array =getSquare(args);
Arrays.sort(array);
Boolean flage = true;
for(double aInt : array){
for(int i=0,j=(array.length-1);i<j;){
double sum = array[i]+array[j]; 
if(aInt == sum){
System.out.println(Math.sqrt(aInt)+", "+Math.sqrt(array[i])+", "+Math.sqrt(array[j]));
flage = false;
break;
}
else if(aInt > sum)
i++;
else
j--;
}
}
if(flage)
System.out.print("No such solution exist");
}
}

Let me know your thoughts

2 comments: