我写了一个代码来计算长度之和
syra(1) = 1
syra(2) = n + syra(n/2) if n%2==0
syra(3) = n + (n*3) + 1
例如
以下是代码:
public static int lengths(int n) throws IllegalArgumentException{
int syra = n;
int count = 0;
int sum = 0;
if (syra < 1){
throw new IllegalArgumentException("Value must be greater than 0");
}else{
for (int i=1; i<=syra; i++){
count = i;
sum++;
while (count > 1){
if ((count % 2) == 0){
count = count / 2;
sum++;
}else{
count = (count * 3) + 1;
sum++;
}
}
}
}
return sum;
}
问题是,如果我用大值(例如700000)爆炸长度,则需要很长时间并且对于已经出现在syra(3)中的syra(10),syra(5)......重复步骤。
如何微调代码以存储重叠序列的某些临时(数组)?
好的,根据信息,这是我的另一个带数组的修改代码,为什么它会产生数组索引超出范围的错误?
public class SyraLengths{
public static void main (String[]args){
lengths(3);
}
public static int lengths(int n) throws IllegalArgumentException{
int syra = n;
int count = 0;
int sum = 0;
int [] array = new int [syra+1];
array[0] = 0;
if (syra < 1){
throw new IllegalArgumentException("Value must be greater than 0");
}else{
for (int i=1; i<=syra; i++){
count = i;
sum++;
while (count > 1){
if(array[count] !=0){sum = sum + array[count];}
else if ((count % 2) == 0){
count = count / 2;
array[count]=sum;
sum++;
}else{
count = (count * 3) + 1;
array[count]=sum;
sum++;
}
}
}
}return sum;
}
}
答案 0 :(得分:3)
使用HashMap<Integer, Integer>
存储您已计算的结果,并在尝试重新计算之前查找值。这种技术称为memoization。
答案 1 :(得分:1)
您要执行的技术称为memoization。
您需要在某些数据结构中存储这些较小调用的输出,然后使用它而不是反复计算。
考虑使用LinkedHashMap特殊构造函数和accessOrder=True
以及overrriden removeEldestEntry()方法。阅读javadoc LinkedHashMap。这里有很好的描述。
这样做,您可以轻松地保留那些最常用的值并保持缓存合理的小(即大多使用1000个元素)。