gpt4 book ai didi

java - 创建一种有效的求和方式

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:22:54 26 4
gpt4 key购买 nike

我写了一个代码来计算长度的总和

syra(1) = 1

syra(2) = n + syra(n/2) 如果 n%2==0

syra(3) = n + (n*3) + 1

例如。

  • syra(1) 将生成 1
  • syra(2) 将生成 2 1
  • syra(3) 将生成 3 10 5 16 8 4 2 1
  • lengths(3) 将是所有 syra(1),syra(2),syra(3) 的总和,即 11。

代码如下:

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;
}

最佳答案

使用 HashMap<Integer, Integer>存储您已经计算的结果,并在尝试重新计算它们之前在那里查找值。这种技术被称为 memoization .

关于java - 创建一种有效的求和方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7648357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com