Leading and Trailing LightOJ - 1282 (n^k 的前三个数)

You are given two integers: n and k, your task is to find the most significant three digits, and least significant three digits of nk.

Input
Input starts with an integer T (≤ 1000), denoting the number of test cases.

Each case starts with a line containing two integers: n (2 ≤ n < 231) and k (1 ≤ k ≤ 107).

Output
For each case, print the case number and the three leading digits (most significant) and three trailing digits (least significant). You can assume that the input is given such that nk contains at least six digits.

Sample Input
5
123456 1
123456 2
2 31
2 32
29 8751919
Sample Output
Case 1: 123 456
Case 2: 152 936
Case 3: 214 648
Case 4: 429 296
Case 5: 665 669

题意是求出 n^k 的前3 个数 和 后3个数
刚开始看到的时候后三个数好求,可以快速幂取余得到
对于前三个数,需要利用到数学的变形
首先,对于任意的一个数都可以转化成
10^x (x 为浮点数) = 10^a * 10^b (a,b 也是浮点数)的形式,
其中 10 ^ a 表示结果的位数,10^b 表示对应位的值。所以可以先求到 x 的值,再求到 b 的值,求到 10^b ,即求到了该数对应位置的值(浮点数),再乘以系数,就能得到前3位的值;

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<algorithm>

#define ll long long
#define inf 0x3f3f3f3f
#define manx 1000007  // 1e6+7

using namespace std;

int quick_pow(int n,int k)
{
    ll tmp = n % 1000;
    ll res = 1;
    while( k )
    {
        if( k % 2 )
            res = ( res * tmp) % 1000;
        tmp = ( tmp * tmp) % 1000;
        k /= 2;
    }
    return res;
}
int main()
{
    int t;
    ll n,k;
    scanf("%d",&t);
    for(int i = 1; i <= t; i ++) 
    {
        scanf("%lld%lld",&n,&k);

        double tmp = (double)k*log10(n*1.0); // 求出 x 的值 
        tmp = tmp - (int)tmp;                // 求出 x 的小数部分 
        tmp = pow(10.0,tmp);                 // n^k = 10^x = 10^a * 10^b  (a 为整数部分,b 为小数部分) 

        int ans1 = (int) (tmp * 100.0);   
        int ans2 = quick_pow(n,k);

        printf("Case %d: %d %03d\n",i,ans1,ans2);// 后三位保留3位输出 
    }
    return 0;
}

对于求前三位的表达式也可以这样写

int ans1 = (int)pow(10.0,2.0 + fmod(k*log10(n*1.0),1) ); // fmod(a,b)  求浮点数的余数 ,返回  a -  b * (a / b);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值