我试图制定一种算法来找到第 n 个 Hardy-Ramanujan 数(一个可以以多种方式表示为 2 个立方体的总和的数字)。除了我基本上用另一个立方体检查每个立方体,看看它是否等于另外 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;
}