数论--Leading and Trailing

本文介绍了一种计算特定幂次运算结果的前三位数和后三位数的方法,利用快速幂取模和数学技巧解决算法问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

F - Leading and Trailing

 

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的前三位数和后三位数,求出后三位数并不困难,只需要快速幂取模1000即可,

难点在于求前三位。

n^m一定可以转化为10^a,将a分为整数部分x和小数部分y,则10^a=10^x*10^y,因为0=<y<1,所以1=<10^y<10,由此可见,10^x即为科学计数法中的权值,所以10^y*100即为n^m的前三位数。

其中为分离a中的小数部分,用了小数模除函数 fmod();

#include<stdio.h>
#include <algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<deque>
#include<ctype.h>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<algorithm>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;

ll qpow(ll n,ll m)
{
    ll ans=1;
    while(m)
    {
        if(m&1)
            ans=(ans*n)%1000;

        n=(n*n)%1000;
        m/=2;
    }
    return ans;
}

int main()
{
    int t;
    scanf("%d",&t);
    for(int k=1;k<=t;k++)
    {
        ll n,m;
        scanf("%lld %lld",&n,&m);

        ll last=qpow(n%1000,m);
        ll first=pow(10,fmod(m*log10(n*1.0),1))*100;

        printf("Case %d: %03lld %03lld\n",k,first,last);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值