Java Program Compile time issue. Runs fine for smaller integer but does not run for a large integer

94 Views Asked by At
  1. Look at the code below for Find how many Cardano Triplets exist such that a+b+c<=n

  2. The function is to find out the total cardano triplet, help me optimizing it for larger values Integer

         private static boolean isTrue(long a, long b, long c) {
             long res = ((8 * a * a * a) + (15 * a * a) + (6 * a) - (27 * b * b * c));
             //double res=((Math.cbrt(a+(b*Math.sqrt(c))))+(Math.cbrt(a-(b*Math.sqrt(c)))));
             return res == 1;
         }
    

3.The below function returning triplet to function isTrue(...) and updating global counter variable private static int counter=0;

private static long countCardano(long n) {
    long c;
    boolean b;
    for (long i = 2; i <= n; i++) {
        for (long j = 1; j <= n; j++) {
            for (long k = 5; k <= n; k++) {
                if ((i + j + k) <= n) {
                    if (isTrue(i, j, k)) {
                        //System.out.println("("+i+","+j+","+k+")");
                        counter++;
                    }
                }
            }
        }

    }
    return counter;
}
1

There are 1 best solutions below

2
On

I would try to reduce the number of iterations based on the if((i+j+k)<=n) condition. So, if this condition is false, clearly increasing k won't respect the condition neither, so i would add a break on the else branch. Similar to that, i would add a condition for (i+j)<n, since adding a positive k to this won't respect the condition neither, so on the else branch of that, i would break again.

So the code would look like that :

private static long countCardano(long n) {
    long c;
    boolean b;
    for(long i=2;i<= n-6;i++) //n-6 because j starts from 1 and k from 5 {
        for(long j=1;j<=n-2;j++) {
            if ((i+j) > (n-5)) break;
            for(long k=5;k<=n-3;k++) {
                if((i+j+k)<=n) {
                  if(isTrue(i,j,k)) {
                    counter++;
                  }
                } else {
                  break;
                }
            }
        }
        
    }
    return counter;
}