3

现在我已经完成了查找 23 组 xyz 值满足条件 x^3+y^3=1+z^3 & x

int setsFound = 0;
System.out.println("The first 23 sets ordered by increasing x.");
for (long x = 1; setsFound < 23; x++) {
  for (long z = x + 1; z<x*x; z++) {
    long y = (long) Math.pow((1 + z*z*z - x*x*x), 1f/3f);
    if (x * x * x == 1 + z * z * z - y * y *y && x<y && y<z) {
      setsFound++;
      System.out.println("X: " + x + ", Y: " + y + ", Z: " + z);
    }
  }
}

但是我的代码效率很低,有人可以帮我解决这个问题吗?

4

2 回答 2

2

这是一个工作代码:

  int setsFound = 0;
  System.out.println("The first 23 sets ordered by increasing x.");
  for (long z = 1; setsFound < 23; z++) {
     for (long y = z - 1; y > 0; y--) {
        long x = (long) Math.pow((1 + z * z * z - y * y * y), 1f/3f);
        if(y <= x) break;
        if (x * x * x == 1 + z * z * z - y * y *y) {
           setsFound++;
           System.out.println("X: " + x + ", Y: " + y + ", Z: " + z);
        }
     }
  }

旧的几个问题:

  1. 1/3 == 0(因为它是整数除法)//使用 1f/3f
  2. x 和 z 交换 - 你想要 z > x,而不是相反
  3. (long)Math.pow(4*4*4, 1.0/3) == (long)3.9999999999999996 == 3 // 使用圆形
于 2011-08-02T07:17:46.563 回答
2

如果你以另一种方式开始,通过将 Y 和 Z 增加到一个极限,使 X < Y < Z,你可以获得一些效率。一旦 Z^3 > X^3 + Y^3 + 1,由于三次函数的凹度,您可以跳到下一个 Y 值。

C# 中的这个实现在笔记本电脑上运行得非常快:

        UInt64 setsFound = 0;
        UInt64 xlim = 10000;
        UInt64 ylim = 1000000;
        UInt64 zlim = 10000000;

        //int ctr = 0;
        Console.WriteLine("The first 23 sets ordered by increasing x.");

        Parallel.For(1, (long)xlim, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
        //for (UInt64 i = 0; i < xlim; i++)
        {
            UInt64 x = (UInt64)i;
            UInt64 xCu = x * x * x;
            int zFails = 0;
            for (UInt64 y = x + 1; y < ylim; y++)
            {
                UInt64 yCu = y * y * y;
                zFails = 0;
                for (UInt64 z = y + 1; z < zlim & zFails < 1; z++)
                {
                    UInt64 zCu = z * z * z;
                    if (xCu + yCu - zCu == 1)
                    {
                        Console.WriteLine(String.Format("{0}: {1}^3 + {2}^3 - {3}^3 = 1", setsFound, x, y, z));
                        setsFound++;
                    }
                    else if (zCu > xCu + yCu - 1)
                    {
                        zFails++;
                    }
                }
            }
        }
        );

显然你可以取出并行化。此外,这里是该集合中的前 19 个元素(计算机仍在运行,稍后我将尝试发布最后 4 个):

输出 http://desmond.yfrog.com/Himg640/scaled.php?tn=0&server=640&filename=8qzi.png&xsize=640&ysize=640

于 2011-08-02T18:34:42.530 回答