Finding all the Pythagorean quadruples faster when a, b or c <= 1000

abhimanyue :

I'm trying to get all the Pythagorean quadruples:

a^2 + b^2 + c^2 = d^2 when a, b, c <= 1000,

My code generates all of them (85490) but it takes around 10 minutes.

I am trying to reduce the execution time. How can I improve the execution time?. Any suggestion please.

Here is my code.

   static int isSquare(int n)
   {
      int m = (int) Math.sqrt(n);

      return m * m == n ? m : 0;
   }

   static List<List<Integer>> allQuadraples = new ArrayList<>();

   static int findQuadraples(int range)
   {
      int total = 0;

      for (int a = 1; a <= range; a++)
         for (int b = 1; b <= range; b++)
            for (int c = 1; c <= range; c++)
            {
               int sum = a * a + b * b + c * c;

               int d = isSquare(sum);

               if (d != 0) // a possible Quadruple
               {
                  List<Integer> oneQuadraple = new ArrayList<>(Arrays.asList(a, b, c, d));
                  Collections.sort(oneQuadraple); // sorting before insertion for comparing later
                  if (!allQuadraples.contains(oneQuadraple))
                  {
                     System.out.println(oneQuadraple);
                     allQuadraples.add(oneQuadraple);
                     total++;
                  }
               }
            }

      return total;
   }
Manoj Banik :

So, if you still need to store all the quadruples then this is the new function, (Thanks to Damien).

It took only 1.5 sec. for finding and storing all 85490.

   static int findQuadraples(int range)
   {
      int total = 0;

      for (int a = 1; a <= range; a++)
         for (int b = a; b <= range; b++)
            for (int c = b; c <= range; c++)
            {
               int sum = a * a + b * b + c * c;
               int d = isSquare(sum);

               if (d != 0) // a possible Quadruple
               {
                  //System.out.println(Arrays.asList(a, b, c, d));
                  allQuadraples.add(Arrays.asList(a, b, c, d));
                  total++;
               }
            }

      return total;
   }

Without saving into an ArrayList, it takes 1.3 sec.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3660&siteId=1