假设我们要计算一些斐波那契数,以 997 为模。
因为n=500在 C++ 中我们可以运行
#include <iostream>
#include <array>
std::array<int, 2> fib(unsigned n) {
if (!n)
return {1, 1};
auto x = fib(n - 1);
return {(x[0] + x[1]) % 997, (x[0] + 2 * x[1]) % 997};
}
int main() {
std::cout << fib(500)[0];
}
Run Code Online (Sandbox Code Playgroud)
在 Python 中
def fib(n):
if n==1:
return (1, 2)
x=fib(n-1)
return ((x[0]+x[1]) % 997, (x[0]+2*x[1]) % 997)
if __name__=='__main__':
print(fib(500)[0])
Run Code Online (Sandbox Code Playgroud)
两者都可以毫无问题地找到答案 996。我们采用模数来保持合理的输出大小,并使用对来避免指数分支。
对于n=5000,C++ 代码输出 783,但 Python 会抱怨
RecursionError: …Run Code Online (Sandbox Code Playgroud) 下面的 C++ 程序
#include <iostream>
int main() {
for(int i=0; i<5; i++) for(int j=0; j<5; j++){
if(i==1) if(j==2) std::cout << "A " << i << ' ' << j << std::endl;
else std::cout << "B " << i << ' ' << j << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产出
B 1 0
B 1 1
A 1 2
B 1 3
B 1 4
Run Code Online (Sandbox Code Playgroud)
由此我推断“else”语句指的是第二个“if”。
C++ 标准中是否描述了这种行为?有没有理由以这种方式实施它?我直觉地认为“else”指的是第一个“if”。