Java 我如何让我的迭代算法工作?
我正在编写一个迭代算法,使用公式Tn=Tn-1+Tn-3生成序列 {0,1,2,2,3,5,7,10,15,22,32,47,69,101}等等。我不知道如何做到这一点,但这是我尝试过的:Java 我如何让我的迭代算法工作?,java,algorithm,iteration,Java,Algorithm,Iteration,我正在编写一个迭代算法,使用公式Tn=Tn-1+Tn-3生成序列 {0,1,2,2,3,5,7,10,15,22,32,47,69,101}等等。我不知道如何做到这一点,但这是我尝试过的: public long calculate(long n) { if (n <= 0) { return 0; } if (n == 1) { return 1; } if (n == 2){ return
public long calculate(long n) {
if (n <= 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (n == 2){
return 2;
}
int firstValue = 1;
int secondValue = 1;
int thirdValue;
for (int i = 2; i < n; i++) {
thirdValue = firstValue;
firstValue += secondValue;
secondValue = thirdValue;
}
return firstValue;
公共长计算(长n){
如果(n对我来说,它看起来像你的公式
n = 2n-4
但是数字不匹配。您不能无限期地添加变量,如forthValue
来解决此类问题
这看起来像这样:
public class Test {
public long calculate(long n) {
if (n <= 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (n == 2){
return 2;
}
return calculate(n - 1) + calculate(n - 3);
}
public static void main(String[] args) {
Test testClass = new Test();
for (int i=0; i < 10; i++) {
System.out.println(testClass.calculate(i));
}
}
}
公共类测试{
公共长计算(长n){
如果(n我制作了一个JavaScript副本,但您肯定可以专注于算法。您的forthValue
可以是每次迭代的结果(firstValue
+thirdValue
),在一次迭代完成后,我们交换值,以便:-
thirdValue
变成secondValue
secondValue
变为firstValue
firstValue
成为结果
以下工作将起作用:-
//n=n-1+n-3
函数计算(n){
如果(n(n-1)+(n-3)->2n-4,并且很容易作为迭代算法实现,但是看到您的代码,我不确定您是否想到了这一点
public long calculate(long n) {
long sum = 0;
for (int i = 0; i < n; i++) {
sum = 2 * sum - 4;
}
return sum;
}
公共长计算(长n){
长和=0;
对于(int i=0;i
我不能将此作为注释发送…代表低…n=(n-1)+(n-3)
不是一个序列。它是一个可以简化为n=4
的公式。但我写道它是一个公式(…使用公式n=(n-1)+(n-3))我知道如何将其作为递归算法编写,但对于这一个,我想将其作为迭代算法编写,但谢谢:)