Rai*_*lin 4 java math performance hardy-ramanujan
我试图制作一个算法来找到第n个Hardy-Ramanujan数(一个可以多个方式表示为2个立方体之和的数字).除了我基本上用另一个立方体检查每个立方体以查看它是否等于另外两个立方体的总和.有关如何提高效率的任何提示?我有点难过.
public static long nthHardyNumber(int n) {
PriorityQueue<Long> sums = new PriorityQueue<Long>();
PriorityQueue<Long> hardyNums = new PriorityQueue<Long>();
int limit = 12;
long lastNum = 0;
//Get the first hardy number
for(int i=1;i<=12;i++){
for(int j = i; j <=12;j++){
long temp = i*i*i + j*j*j;
if(sums.contains(temp)){
if(!hardyNums.contains(temp))
hardyNums.offer(temp);
if(temp > lastNum)
lastNum = temp;
}
else
sums.offer(temp);
}
}
limit++;
//Find n hardy numbers
while(hardyNums.size()<n){
for(int i = 1; i <= limit; i++){
long temp = i*i*i + limit*limit*limit;
if(sums.contains(temp)){
if(!hardyNums.contains(temp))
hardyNums.offer(temp);
if(temp > lastNum)
lastNum = temp;
}
else
sums.offer(temp);
}
limit++;
}
//Check to see if there are hardy numbers less than the biggest you found
int prevLim = limit;
limit = (int) Math.ceil(Math.cbrt(lastNum));
for(int i = 1; i <= prevLim;i++){
for(int j = prevLim; j <= limit; j++){
long temp = i*i*i + j*j*j;
if(sums.contains(temp)){
if(!hardyNums.contains(temp))
hardyNums.offer(temp);
if(temp > lastNum)
lastNum = temp;
}
else
sums.offer(temp);
}
}
//Get the nth number from the pq
long temp = 0;
int count = 0;
while(count<n){
temp = hardyNums.poll();
count++;
}
return temp;
}
Run Code Online (Sandbox Code Playgroud)
这些数字有时被称为"出租车"号码:
数学家GH Hardy正在去拜访他在医院的合作者Srinivasa Ramanujan.哈迪对Ramanujan表示,他乘坐1729号车牌的出租车,这看起来很沉闷.对此,Ramanujan回答说1729是一个非常有趣的数字 - 它是两个不同方式中两个数字的立方总和的最小数字.实际上,10 3 + 9 3 = 12 3 + 1 3 = 1729.
由于其立方体求和的两个数字x和y必须都在0和n的立方根之间,因此一个解决方案是对x和y的所有组合的穷举搜索.一个更好的解决方案从x = 0 开始,y是n的立方根,然后重复做出三向决策:如果x 3 + y 3 < n,则增加x,如果x 3 + y 3 > n,则减小y,或者如果是x 3+y 3 = n,报告成功并继续搜索更多:
function taxicab(n)
x, y = 0, cbrt(n)
while x <= y:
s = x*x*x + y*y*y
if s < n then x = x + 1
else if n < s then y = y - 1
else output x, y
x, y = x + 1, y - 1
Run Code Online (Sandbox Code Playgroud)
以下是小于100000的出租车编号:
1729: ((1 12) (9 10))
4104: ((2 16) (9 15))
13832: ((2 24) (18 20))
20683: ((10 27) (19 24))
32832: ((4 32) (18 30))
39312: ((2 34) (15 33))
40033: ((9 34) (16 33))
46683: ((3 36) (27 30))
64232: ((17 39) (26 36))
65728: ((12 40) (31 33))
Run Code Online (Sandbox Code Playgroud)
我在博客上讨论这个问题.