Fibonacci
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1360 Accepted Submission(s): 336
Problem Description
Following is the recursive definition of Fibonacci sequence:
Now we need to check whether a number can be expressed as the product of numbers in the Fibonacci sequence.
Fi=⎧⎩⎨01Fi−1+Fi−2i = 0i = 1i > 1
Now we need to check whether a number can be expressed as the product of numbers in the Fibonacci sequence.
Input
There is a number
T
shows there are
T
test cases below. (
T≤100,000
)
For each test case , the first line contains a integers n , which means the number need to be checked.
0≤n≤1,000,000,000
For each test case , the first line contains a integers n , which means the number need to be checked.
0≤n≤1,000,000,000
Output
For each case output "Yes" or "No".
Sample Input
3 4 17 233
Sample Output
Yes No Yes
Source
题意:
给你一个数n(1<=n<=1000 000 000),判断n的因子能否全部由斐波那契数列中的数组成。
分析:
方法一:可以知道在1~n范围内的斐波那契数只有45个,所以直接dfs搜索因子即可(刚开始一直TLE。。后来发现不需每次都要45个全搜,可以从大到小搜,如果那个数不符合时,后面就不用再搜那个数了)。
code:
#include<stdio.h>
#define N 45
int f[N]={0,1};
int dfs(int k, int fact)
{
if(fact == 1 || fact == 0) return 1;
for(int i=k; i>=3; i--)
if(fact%f[i] == 0)
if(dfs(i,fact/f[i])) return 1;
return 0;
}
int main()
{
int T, n;
for(int i=2; i<N; i++)
f[i] = f[i-1]+f[i-2];
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
puts(dfs(N-1,n) ? "Yes" : "No");
}
return 0;
}
第二种方法:把那45个数互相乘啊乘啊乘,在1e9范围内的所有可能的数都找出来,然后看有没有等于n的;
#include<stdio.h>
#include<vector>
#include<set>
using namespace std;
#define N 45
int main()
{
int T, n, f[N] = {0,1};
for(int i=2; i<N; i++)
f[i] = f[i-1]+f[i-2];
set<int> s;
set<int>::iterator it;
vector<int> v;
s.insert(1);
for(int i=3; i<N; i++)
{
v.clear();
for(long long m=f[i]; m<=1e9; m*=f[i])
{
for(it=s.begin(); it!=s.end(); it++)
{
if(m*(*it) > 1e9) break;
v.push_back(m*(*it));
}
}
for(int i=0; i<v.size(); i++)
s.insert(v[i]);
}
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
if(s.find(n) != s.end() || n==0) puts("Yes");
else puts("No");
}
return 0;
}