#include<iostream>
using namespace std;
double fib(int n) ;
int main()
{
int n;
cin>>n;
double a[20000];
for(int i=0;i<n;i++)cin>>a[i];
double b[20000];
for(int j=0;j<n;j++){
for(int i=0;i<100003;i++)
{
if(fib(i)>a[j]){
b[j]=fib(i-1);
break;
}
}}
for(int i=0;i<n;i++)
cout<<b[i]<<endl;
return 0;
}
double fib(int n)
{
int result[2] = {0,1};
if(n < 2)
return result[n];
double fibOne = 0;
double fibTwo = 1;
double fibN = 0;
int i = 0;
for(i = 2; i <= n; i++)
{
fibN = fibOne + fibTwo;
fibOne = fibTwo;
fibTwo = fibN;
}
return fibN;
}
It should be matrix + fast power!
If you are asking about C++, I think the room for optimization is to replace cin and cout with scanf and printf, or use templates to complete calculations at compile time.
But this question obviously requires optimization beyond the language level. The method is the matrix fast power mentioned above. However, there is also a fibonacci algorithm on sicp that looks very metaphysical. If you are interested, you can take a look:-)
The people above are all talking nonsense. This question actually tests binary search hehe~
-------------Dividing line--------
As a back-end nodejs newbie, I decided to use lua to implement it for you to see
After reading the answer below, I silently changed MAX to 48...
C++14 can use constexpr + array + index_sequence to directly generate the fib array, and then use lower_bound to query.
What are you using double for? Double is a floating point number
Floating point operations are slow
For long integers use long long
You used int, and int can only reach a maximum of 2^31 - 1
So if you encounter some strange m value, the fib you calculated will continue to overflow into a negative number, and then loop endlessly.
Since 1 <= n <= 20000, you can calculate them all first, hard-code them into the source code, and just use binary search.
(The advanced techniques like constexpr above are essentially the same thing, but the compiler does the work during compilation...)
Of course, if you want to get a little more advanced, you can use
n = log(m * sqrt(5)) / log((sqrt(5) + 1) / 2)
as the starting point for your search.Because
fib(n) = round(((sqrt(5) + 1) / 2)^m / sqrt(5))
But in fact, all of the above are meaningless, because fib(48) = 4,807,526,976, which is already larger than 2^32.
So actually you only need unsigned int[48], and you don’t need 20000 bits at all.
You can even hardcode a bunch of if elses to do this question...