0
  1. 看看下面的代码Find how many Cardano Triplets exist such that a+b+c<=n

  2. 该功能是找出总的cardano三元组,帮助我优化它以获得更大的值整数

         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.以下函数返回三元组函数isTrue(...)并更新全局计数器变量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;
}
4

1 回答 1

0

我会尝试根据if((i+j+k)<=n)条件减少迭代次数。所以,如果这个条件是错误的,显然增加k也不会尊重条件,所以我会在else分支上添加一个中断。与此类似,我会添加一个条件 for (i+j)<n,因为向 this 添加一个肯定k也不会尊重条件,所以在 else 分支上,我会break再次这样做。

所以代码看起来像这样:

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;
}
于 2020-09-14T06:59:01.810 回答