两种方法之间的逻辑差异。(计算达到第n个楼梯的方式)

huangapple go评论79阅读模式
英文:

Logical difference between the two approaches. (Count ways to reach the n'th stair)

问题

以下是翻译好的部分:

//---01--------
int mod = (int)1e9+7;
int prev1 = 1;
int prev2 = 1;
for(int i = 2; i <= n; i++){
    prev2 = (prev2 + prev1) % mod;
    prev1 = prev2 - prev1;
}
return prev2;
//---02--------
int mod = (int)1e9+7;
int prev1 = 1;
int prev2 = 1;
for(int i = 2; i <= n; i++){
    int curr = (prev2 + prev1) % mod;
    prev1 = prev2;
    prev2 = curr;
}
return prev2;
英文:

I am trying to count the number of ways to reach the nth stair, starting from the first stair and going up either one or two stairs at a time. The first approach below works fine, but the second does not.

//---01--------
int mod = (int)1e9+7;
int prev1 = 1;
int prev2 = 1;
for(int i = 2; i <= n; i++){
    prev2 = (prev2 + prev1) % mod;
    prev1 = prev2 - prev1;
}
return prev2;
//---02--------
int mod = (int)1e9+7;
int prev1 = 1;
int prev2 = 1;
for(int i = 2; i <= n; i++){
    int curr = (prev2 + prev1) % mod;
    prev1 = prev2;
    prev2 = curr;
}
return prev2;

The second approach doesn't work with large n.

Sample Input Case: n = 87

Output with the second approach:

-334512466

Expected Output:

665487541

答案1

得分: 0

第一个解决方案存在问题,与第二个解决方案相反。第一个解决方案将溢出(不是整数溢出,而是由于错误逻辑导致负值),而第二个解决方案不会。

为了更好地理解,请查看下面对第一个解决方案的更新代码 -

for (int i = 2; i <= n; i++) {
    System.out.println("i : " + i);
    prev2 = (prev2 + prev1) % mod;
    System.out.println("P2 : " + prev2);
    System.out.println("P1 : " + prev1);
    prev1 = prev2 - prev1;
}

以下是上述代码的输出 -

i : 44
P2 : 134903163
P1 : 433494437
i : 45
P2 : -163688111
P1 : -298591274

如果观察这些值,您会发现对于 i=44,由于 mod 函数,prev2 小于 prev1,当您执行 prev1 = prev2 - prev1; 时,会得到负值,因此这个解决方案是错误的。

而第二个解决方案将正常工作,因为没有这种情况。

英文:

Its other way around, your first solution will overflow(not Integer overflow but negative values due to wrong logic) but not second one.

For better understanding see below updated code for your first solution -

for(int i = 2; i &lt;= n; i++){
    System.out.println(&quot;i : &quot;+i);
    prev2 = (prev2 + prev1) % mod;
    System.out.println(&quot;P2 : &quot; +prev2);
    System.out.println(&quot;P1 : &quot; +prev1);
    prev1 = prev2 - prev1;
}

Below is the output of above -

i : 44
P2 : 134903163
P1 : 433494437
i : 45
P2 : -163688111
P1 : -298591274

If you observe the values you can see, for i=44, prev2 is smaller then prev1 because of mod function and when you will do prev1 = prev2 - prev1; you will get negative value so this solution is wrong.

While second solution will work as there is no such case.

huangapple
  • 本文由 发表于 2023年1月9日 14:11:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定