4 条题解

  • -1
    @ 2026-7-14 11:37:51

    这是一题斐波那契数列

    公式:

    A(n)(当前项)=A(n+1)(前一项)+A(n+2)(前前项)

    样例输入

    6
    
    

    样例输出

    8
    
    

    代码实现

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    int n, res;
    int f(int x) {
    	if (x == 1 || x == 2) {
    		res = 1;
    	} else {
    		res = f(x - 1) + f(x - 2);
    	}
    
    	return res;
    }
    
    main(signed) {
    	cin >> n;
    	f(n);
    	cout << res << '\n';
    
    	return 0;
    }
    
    
    
    

    数据更大时:

    样例输入

    50
    
    

    样例输出

    12586269025
    
    

    代码实现

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    const int N = 1e6 + 10;
    
    int n, res, a[N] = {0};
    
    main(signed) {
    	cin >> n;
    	a[1] = 1;
    	a[2] = 1;
    
    	for (int i = 3; i <= n; i++) {
    
    		a[i] = a[i - 1] + a[i - 2];
    	}
      //递推(找规律)
    
    	cout << a[n] << '\n';
    
    	return 0;
    }
    

    第一段代码为递归,第二段代码为递推,递归只要数据超过50就会超时。

    信息

    ID
    30958
    时间
    1000ms
    内存
    256MiB
    难度
    3
    标签
    (无)
    递交数
    70
    已通过
    40
    上传者