hdu1568

http://acm.hdu.edu.cn/showproblem.php?pid=1568

看了半天,没思路,摘了一位dn的,学习了!

15103831_R3jk.gif 15103831_NNpw.gif View Code

    
先看对数的性质,loga(b ^ c) = c * loga(b),loga(b * c) = loga(b) + loga(c);
假设给出一个数10234432,那么log10(
10234432 ) = log10( 1.0234432 * 10 ^ 7 ) = log10( 1.0234432 ) + 7 ;

log10(
1.0234432 )就是log10( 10234432 )的小数部分.

log10(
1.0234432 ) = 0.010063744
10 ^ 0.010063744 = 1.023443198
那么要取几位就很明显了吧
~
先取对数(对10取),然后得到结果的小数部分bit,pow(
10.0 ,bit)以后如果答案还是 < 1000那么就一直乘10。
注意偶先处理了0
~ 20项是为了方便处理 ~

这题要利用到数列的公式:an
= ( 1 / 5 ) * [(( 1 + 5 ) / 2 ) ^ n - (( 1 - 5 ) / 2 ) ^ n](n = 1 , 2 , 3 .....)

取完对数

log10(an)
=- 0.5 * log10( 5.0 ) + (( double )n) * log(f) / log( 10.0 ) + log10( 1 - (( 1 - 5 ) / ( 1 + 5 )) ^ n)其中f = (sqrt( 5.0 ) + 1.0 ) / 2.0 ;
log10(
1 - (( 1 - 5 ) / ( 1 + 5 )) ^ n) -> 0
所以可以写成log10(an)
=- 0.5 * log10( 5.0 ) + (( double )n) * log(f) / log( 10.0 );
最后取其小数部分。

#include
< iostream >
#include
< cmath >
using namespace std;
int fac[ 21 ] = { 0 , 1 , 1 };
const double f = (sqrt( 5.0 ) + 1.0 ) / 2.0 ;
int main()
{
double bit;
int n,i;
for (i = 3 ;i <= 20 ;i ++ )fac[i] = fac[i - 1 ] + fac[i - 2 ]; // 求前20项
while (cin >> n)
{
if (n <= 20 )
{
cout
<< fac[n] << endl;
continue ;
}
bit
=- 0.5 * log( 5.0 ) / log( 10.0 ) + (( double )n) * log(f) / log( 10.0 ); // 忽略最后一项无穷小
bit = bit - floor(bit);
bit
= pow( 10.0 ,bit);
while (bit < 1000 )bit = bit * 10.0 ;
printf(
" %d\n " ,( int )bit);
}
return 0 ;
}

摘自: http://hi.baidu.com/aekdycoin/blog/item/60bbae2b38c6f52ad42af18f.html

转载于:https://my.oschina.net/garyun/blog/602942

猜你喜欢

转载自blog.csdn.net/weixin_34007020/article/details/91774195