Leading and Trailing LightOJ - 1282 (取数的前三位和后三位)

题意:

求n的k次方的前三位 和 后三位 。。。刚开始用 Java的大数写的。。。果然超时。。。

好吧  这题用快速幂取模求后三位  然后用一个技巧求前三位 。。。orz。。。

任何一个数n均可以表示为10a, 其中 a 可以为小数

那么nk 可以表示为10ak  , 令ak == x + y  (其中x为整数 y为小数)  所以 ak - x == y

于x是整数,那么很明显他是用来指定位数的,因为10x肯定是一个10, 100, 10000...之类的数字,也就是说10y才是这个数字的有效部分,我们只要求出10y,然后乘上100最终结果就是我们想要的。

因为n = 10a  所以 a = log10(n),10y就是小数部分,我们用函数fmod(x, 1),返回x的小数部分,然后乘上100即可

fmod返回的是y的值,所以必须计算10y才是真实值,所以直接使用102 * 10y 即pow(10, 2 + y);

代码如下:

#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#define MOD 1000
#define LL long long
#define ULL unsigned long long
#define maxn 100009
#define Pair pair<int, int>
#define mem(a, b) memset(a, b, sizeof(a))
#define _  ios_base::sync_with_stdio(0),cin.tie(0)
//freopen("1.txt", "r", stdin);
using namespace std;
const int LL_INF = 0x7fffffffffffffff,INF = 0x3f3f3f3f;
LL qpow(LL a,LL b)
{
    LL res = 1;
    while(b)
    {
        if(b & 1) res = res * a % MOD;
        a = a * a % MOD;
        b >>= 1;
    }
    return res;
}

int main()
{
    int T;
    int cnt = 0;
    cin>> T;
    while(T--)
    {
        int n, k;
        cin>> n >> k;

        int res = pow(10, 2 + fmod(k * log10(n), 1));

        printf("Case %d: %d %03d\n",++cnt,res,qpow(n,k));

    }


    return 0;
}

猜你喜欢

转载自www.cnblogs.com/WTSRUVF/p/9182565.html