This code is about finding Pythagorean triplets. I take a number as input, and find from 1 to that number, how many Pythagorean triplets exist.
Are there ways this can be optimized? It takes a lot of time, but actually doesn't only provide the output for no
> 10000
import java.util.*;
import java.io.*;
public class Solution
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
HashMap<Integer,Set<Set<Integer>>> mymap=new HashMap<Integer,Set<Set<Integer>>>();
public static void main(String args[])
{
Solution s=new Solution();
try
{
int t=Integer.parseInt(s.in.readLine());
for(int i=0;i<t;i++)
{
int no=Integer.parseInt(s.in.readLine());
s.findAllPythogoreanTriplets(no);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void findAllPythogoreanTriplets(int no) {
if(mymap.containsKey(new Integer(no)))
System.out.println(mymap.get(no).size());
else
{
int [] unsortedData=new int[no];
for(int i=0;i<no;i++)
unsortedData[i]=i+1;
// O(n) - Square all the elements in the array
for (int i = 0; i < unsortedData.length; i++)
unsortedData[i] *= unsortedData[i];
// O(n logn) - Sort
int [] sortedSquareData = unsortedData;
// O(n2)
Set<Set<Integer>> triplets = new HashSet<Set<Integer>>();
for (int i = 0; i < sortedSquareData.length; i++) {
Set<Set<Integer>> pairs = findAllPairsThatSumToAConstant(sortedSquareData, sortedSquareData[i]);
for (Set<Integer> pair : pairs) {
Set<Integer> triplet = new HashSet<Integer>();
for (Integer n : pair) {
triplet.add((int)Math.sqrt(n));
}
triplet.add((int)Math.sqrt(sortedSquareData[i])); // adding the third element to the pair to make it a triplet
triplets.add(triplet);
}
}
mymap.put(no,triplets);
System.out.println(triplets.size());
}
}
public Set<Set<Integer>> findAllPairsThatSumToAConstant(int [] sortedData, int constant) {
// O(n)
Set<Set<Integer>> pairs = new HashSet<Set<Integer>>();
int p1 = 0; // pointing to the first element
int p2 = sortedData.length - 1; // pointing to the last element
while (p1 < p2) {
int pointersSum = sortedData[p1] + sortedData[p2];
if (pointersSum > constant)
p2--;
else if (pointersSum < constant)
p1++;
else {
Set<Integer> set = new HashSet<Integer>();
set.add(sortedData[p1]);
set.add(sortedData[p2]);
pairs.add(set);
p1++;
p2--;
}
}
return pairs;
}
}