递归 - 整数拆分为斐波拉契数列的和

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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值