Look at the code below for
Find how many Cardano Triplets exist such that a+b+c<=n
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;
}
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 increasingk
won't respect the condition neither, so i would add a break on theelse
branch. Similar to that, i would add a condition for(i+j)<n
, since adding a positivek
to this won't respect the condition neither, so on the else branch of that, i wouldbreak
again.So the code would look like that :