Fibonacci sequence (4)
Time Limit:
1000
ms | Memory Limit:
65535
KB
Difficulty:
4
- describe
-
Math prodigy Xiao Ming finally put the Fibonacci sequence from 0 to 100000000 (f[0]=0, f[1]=1; f[i] = f[i-1]+f[i-2](i>=2) ) values are all memorized.
Next, CodeStar decided to test him, so he had to say the answer every time he asked a number, although some of the numbers were too long. So it is stipulated that if there are more than 4 digits, just say the first 4 digits (high 4 digits), but CodeStar can't remember it. So he decided to write a program to test whether Xiao Ming said is correct.
- enter
-
Enter a number of numbers n (0 <= n <= 100000000), one line per number. Read to end of file.
- output
-
Output the first 4 digits of f[n] (if there are less than 4 digits, output all of them).
- sample input
-
0 1 2 3 4 5 35 36 37 38 39 40
- Sample output
-
0 1 1 2 3 5 9227 1493 2415 3908 6324
1023
-
-
-
-
The properties of logarithms, loga(b^c)=c*loga(b), loga(b*c)=loga(b)+loga(c); suppose a number 10234432 is given,
then log10(10234432)=log10 (1.0234432*10^7)[represent this number in scientific notation]=log10(1.0234432)+7;
log10(1.0234432) is the fractional part of log10(10234432).
log10(1.0234432)=0.010063744 (generated by taking logarithms) The number must be a decimal)
and then take it to the power: 10^0.010063744=1.023443198, then subtract the integer part, and the rest is the fractional part, so to take the first 4 digits, you only need to multiply the fractional part by 1000. -
#include<iostream>//Standard input and output functions #include<math.h>//Use log10 sqrt p using namespace std;//Introduce standard namespace int p[30]; void db() { p[0]=0;p[1]=1; for(int i=2;i<25;i++) { p[i]=p[i-2]+p[i-1];//Use recursion to deduce the first 20, why is it 20, because fn[20] is the largest four-digit number in the entire sequence } } intmain() { int n; db(); while(cin>>n) { if(n<=20) cout<<p[n]<<endl;//If it does not exceed 4 digits, output else{ double t=(1+sqrt(5))/2.0; double r=n*log10(t)-0.5*log10(5);//Remove the last item in the general term formula, and take log10 r-=floor(r);//Take the fractional part of the result r=pow(10,r);//Restore even the fractional part of scientific notation int result=(int)(r*1000);//*1000 rounding is the result cout<<result<<endl; } } }
-