Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1568
Output the first four bits of the method unexpectedly, so reproduced the method: (Original address http://jingyan.baidu.com/article/f3e34a128e48acf5ea65355b.html)
Test instructions: The first four bits of the output Fibonacci array,n<=100000000; ideas:
First: To see the data range of this problem, the time complexity of 0 (n) is not possible.
And then think of the array can be used to store it? n<=100000000, the number is too big, even if the expression, will also time out.
Think about whether there is a cyclic section, but the first four is related to the following several (can produce a carry), not only the first four bits;
Finally think: Fibonacci number must have formula can be calculated as follows:
- Think about how to produce the top 4 bits.
First look at the properties of logarithms, Loga (b^c) =c*loga (b), Loga (b*c) =loga (b) +loga (c); Suppose given a number 10234432,
Then log10 (10234432) =log10 (1.0234432*10^7) "means this number in scientific notation" =LOG10 (1.0234432) +7;
LOG10 (1.0234432) is the small part of log10 (10234432).
LOG10 (1.0234432) =0.010063744 (the number produced by the logarithm must be a decimal)
Fetch Power again: 10^0.010063744=1.023443198
Then it is better to take the first few.
To take the logarithm of a formula:
The last item is less than 0 and is small and can be used without calculation
Steps:
First take the logarithm (to 10), and then get the result of the decimal part Bit,pow (10.0,bit) Later if the answer is still <1000 then always multiply by 10. Note that I first processed the 0~20 item for ease of handling ~
Code:
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <cmath>5 6 using namespacestd;7 8typedefLong LongLL;9 intf[ +];//Fibonacci The first 20 items are four digits, 21 items are not in the future.Ten intN; One A voidinit () { -f[0] =0; -f[1] =1; the for(inti =2; I < +; i++) { -F[i] = f[i-1] + f[i-2]; - } - } + - voidsolve () { + if(N < +) { Aprintf"%d\n", F[n]); at } - Else { - intanswer; - - //finding the logarithm of a formula - DoubleAns =-0.5* LOG10 (5.0) + N * LOG10 ((1+SQRT (5))/2); inAns-= floor (ans);//get the small part of ans -Ans = POW (Ten, ans);//take a power once to get the same number of original digits with only one integer toAnswer =int(ANS * +);//Top 4 digits +printf"%d\n", answer); - } the } * $ intMain () {Panax Notoginseng init (); - while(~SCANF ("%d", &N)) { the solve (); + } A return 0; the}
[HDOJ1568] Fibonacci