[英]Program to disintegrate a number into fibonacci numbers
I am struggling to write a program in C. I want to disintegrate a number (only if it can be disintegrated) into a smaller numbers which can only be fibonacci numbers. 我正在努力用C语言编写一个程序。我想将一个数字分解(只有可以分解),而这个较小的数字只能是斐波那契数字。 For example :
例如 :
If I have a number n = 20 then my output should be 1,1,2,3,5,8 so when I add these smaller fibonacci numbers it gives me number 20. 如果我有一个数字n = 20,那么我的输出应该是1、1、2、3、5、8,所以当我将这些较小的斐波那契数字相加时,它得到的数字是20。
Every integer has a representation as a sum of unique Fibonacci numbers. 每个整数都有唯一的斐波那契数之和。 This is easy to prove by induction: if such a representation exists for all numbers up to Fib(n), then Fib(n)+k for k in 1, 2, ..., Fib(n-1) has the representation of Fib(n) + (representation for k).
这很容易通过归纳法证明:如果存在直到Fib(n)的所有数字都有这样的表示,则在1,2,...,Fib(n-1)中有k的Fib(n)+ k Fib(n)+(k的表示)的乘积。 The proof suggests a simple recursive algorithm for finding the presentation for N: pick the greatest Fibonacci number that is less than N, say it's Fib(k).
证明建议了一种简单的递归算法来查找N的表示形式:选择小于N的最大斐波那契数,即Fib(k)。 Then find the representation for N-Fib(k).
然后找到N-Fib(k)的表示。
It can be reduced to subset-sum problem , where the set is the fibonacci numbers smaller/equals the given number. 它可以简化为子集和问题 ,其中集合是斐波那契数小于/等于给定数。
First generate all numbers smaller/equals the given number n
. 首先生成所有小于或等于给定数字
n
数字。 C-like pseudo code: 类似C的伪代码:
int i = 1;
int* arr = //sufficiently large array
arr[0] = arr[1] = 1;
while (arr[i] <= n) {
i++;
arr[i] = arr[i-1] + arr[i-2];
}
After this, you have arr
that contains all "candidates", and need to invoke subset-sum algorithm to solve it, using the following recursive calls 此后,您将拥有包含所有“候选对象”的
arr
,并需要使用以下递归调用来调用子集和算法来解决该问题
D(x,i) = false x<0
D(0,i) = true
D(x,0) = false x != 0
D(x,i) = D(x,i-1) OR D(x-arr[i]-1,i)
You later, just need to retrace your steps and find out the actual number used by the DP: 稍后,您只需回顾您的步骤并找出DP使用的实际编号:
Pseudo code: 伪代码:
x = n;
i = number_of_candidates;
while (i>0) {
if (x >= arr[i] && DP[i][x-arr[i]]) {
//arr[i] is in the solution, add it
x = x-arr[i];
}
i--; //do it for both cases, successful 'if' or not.
}
Total complexity of the answer is O(nlogn)
, and the bottleneck is the DP solution. 答案的总复杂度为
O(nlogn)
,而瓶颈是DP解决方案。
Note that the number of "candidates" is in O(logn)
, since the i
th fibonacci number is in O(phi^i)
. 注意,“候选”的数目以
O(logn)
,因为第i
个斐波那契数以O(phi^i)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.