Fibonacci
时间限制: 2 Sec 内存限制:128 MB
题目描述
Fibonacci numbers are well-known as follow:
Now given an integer N, please find out whether N can be represented as the sum of several Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers.
输入
Multiple test cases, the first line is an integer T (T<=10000), indicating the number of test cases.
Each test case is a line with an integer N (1<=N<=109).
输出
One line per case. If the answer don’t exist, output “-1” (without quotes). Otherwise, your answer should be formatted as “N=f1+f2+…+fn”. N indicates the given number and f1, f2, … , fn indicating the Fibonacci numbers in ascending order. If there are multiple ways, you can output any of them.样例输入
4 5 6 7 100
样例输出
5=5 6=1+5 7=2+5 100=3+8+89 一开始没有真正认识到【任何正整数可以表示为若干个不连续的 Fibonacci 数之和。】这个定理的真正含义所以走了很大的弯路,其实这道题用递归就可以解决。 只需要依次分解不是斐波拉契数的数就可以了。 【给自己看的内容:这份代码只是比赛时候写的代码,还不是十分简洁,必须尽快修正!!!】 以下是代码:#include<iostream> #include<string> #include<cstring> #include<vector> #include<algorithm> #include<stack> using namespace std; #define N 91 long long fib[N] = { 1,2 }; void fi() { for (int i = 2; i < N; i++) fib[i] = fib[i - 2] + fib[i - 1]; } int big(long long n) { int k; for (k = 0; k < N; k++) if (fib[k + 1] > n)return k;//找到比N小的最大的数 } void solu(long long n, bool first) { int k = big(n); long long left = n - fib[k]; if (first) { cout << n << "="; if (!left)//如果刚好是斐波拉契数 { cout << n ; return; } if (left>0) solu(left, false); cout << fib[k]; } else { if (left>0) solu(left, false); cout << fib[k]<< "+" ; } return; } int main() { fi(); int T; cin >> T; while (T--) { long long n; int k; cin >> n; solu(n, true); cout << endl; } return 0; }
参考来源:http://blog.csdn.net/acdreamers/article/details/8586135
递归 - 整数拆分为斐波拉契数列的和
最新推荐文章于 2021-11-24 21:49:03 发布