I have been taking part in competitive coding of csacademy site. There I have come up with some question I guess it is well-known to most of you, which is about the following : given a number of stairs, calculating the number of ways we can traverse them; with each step of foot, one may land on the next step , or may skip one step and land on the following step.
As you probably know , it involves the Fibonacci method.
The base cases are as the following:
-in case of one step given - we have one way to traverse it.
-in case of two steps given - we have two ways to traverse them.
The input will start with a single line containing one integer t (1≤t≤5) specifying the number of instances of the problem. Each subsequent line will contain one instance of the problem – a single integer n (1≤n≤22000) specifying the number of steps in the stair case.
For each instance of the problem, the program must output one line containing a single integer – the number of ways the steps could be traversed.
The code I wrote for this problem with cpp - fails in some three test which I can not investigate since I run it with the platform of csacadamy site :
#include <iostream>
using namespace std;
int main()
{
long long int t, n,res=0;
cin>>t;
while (t>0) {
cin>>n;
if (n==1)
cout<<1<<endl;
else if (n==2)
cout<<2<<endl;
else{
long long int temp1=1,temp2=2;
for (long long int i=2;i<n;i++){
res = temp1 + temp2 ;
temp1=temp2;
temp2=res;
}
cout<<res<<endl;
}
t--;
}
return 0;
}
However, I wrote the exact same code with Python, and it runs in 100% well:
t = int(input())
for i in range(t):
res = 0
n = int(input())
if n == 1:
print(1)
continue
if n == 2:
print(2)
continue
temp1 =1
temp2 =2
for j in range(2,n):
res = temp1 + temp2
temp1 = temp2
temp2 = res
print(res)
May you please help me know the reason for that?