LightOJ1282_Leading and Trailing _对数求前三位数&快速幂

来源:互联网 发布:windows查看显存 编辑:程序博客网 时间:2024/06/15 12:50

题意

给出两个正整数 n,k。分别输出 n 的 k 次方的前三位数和后三位数。

思路

后三位数简单,快速幂取余即可,特别的需要注意以下三位,注意添加前导0。
对于前三位,由于数极大,考虑用对数的方法解决。

考察公式 x = log10(n^k) = k * log10(n)
则有 10^x = n^k
若将 x 分解为整数部分 a,和小数部分 b.
则有 x = a + b, n^k = 10^b * 10^a.
其中 10^a = 1000…, 而 10^b 则是 n^k 除以 1000…后不大于0的一个数。
本题要求的是前三位,则 10^(b+2) 取整就可以得到结果。

这里要介绍两个函数,都在 cmath 库中
1. pow 中第二个参数可以是小数
2. fmod 暂理解为对浮点数取余的操作。特别的,fmod(a,1.0)表示取 a 的小数部分。

计算过程,首先根据 x = k * log10(n)容易算出 x ,然后对 x 取小数部分,最后代入公式 10^(b+2) 即可。

题目链接

Vjudge链接
https://vjudge.net/contest/169048#problem/E

AC代码

#include<cstdio>#include<iostream>#include<cmath>using namespace std;typedef long long LL;const LL maxn = 1e31 + 100;LL t, n, k;int quick_power(LL n, LL k){    LL res = 1, exp = k;    while(exp > 0)    {        if(exp & 1) res = res * n % 1000;        n = n * n % 1000;        exp >>= 1;    }    return res;}int main(){    scanf("%lld", &t);    for(int cas= 1; cas<= t; cas ++)    {        scanf("%lld %lld", &n, &k);        int s = (int)pow(10.0, 2.0 + fmod(k * log10(n), 1.0));        int e = quick_power(n, k);        printf("Case %d: %d %03d\n", cas, s, e);    }    return 0;}
阅读全文
0 0
原创粉丝点击