E.Function
Define a functionf(n)=(f(n-1)+1)/f(n-2). You already got f(1) and f(2). Now, give you a numberm, please find the value of f(m).
Input
There are several test cases. Each case containsthree integers indicating f(1), f(2) and m ( 1 <= f(1), f(2), m <=1000,000,000).
Output
For each case, please output the value off(m), rounded to 6 decimal places.
SampleInput
1 1 3
SampleOutput
2.000000
----------------------------------------------------------------------------------------------------------
解题报告:
根据数学递推公式,可得:
1) f(n) = ( f(n-1) + 1) / ( f(n-2) )
2) f(n+1) = ( f(n-1) + f(n-2) + 1 ) / ( f(n-1) * f(n-2) )
3) f(n+2) = ( f(n-2) + 1 ) / f(n-1)
4) f(n+3) = f(n-2)
5) f(n+4) = f(n-1)
6) f(n+5) = ( f(n-1) + 1) / ( f(n-2) ) = f(n)
7) 由此可见,该递推公式是 以5为周期 的周期函数。
8) 于是……
优化:
- 运算最快的代码,应该是 %5 后,套用以上的公式 运算输出。
- 编写最快的代码,应该是 进行5次循环(实际上只需求出f(n),f(n+1) ,f(n+2)就行),然后 %5 调用。
----------------------------------------------------------------------------------------------------------
代码:
#include<stdio.h>
int main()
{
double a,b,sum;
long n;
while( EOF != scanf("%lf%lf%ld",&b,&a,&n) )
{
n=(n+2)%5;
if( 0==n ) sum=(a+1)/b;
else if( 1==n ) sum=(a+b+1)/(a*b);
else if( 2==n ) sum=(b+1)/a;
else if( 3==n ) sum=b;
else sum=a;
printf("%.6lf\n",sum);
}
return 0;
}