牛客网 求root(N,k)(二分快速幂、清华机试)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunlanchang/article/details/88559180

题目描述

N<k时,root(N,k) = N,否则,root(N,k) = root(N’,k)。N’为N的k进制表示的各位数字之和。输入x,y,k,输出root(x^y,k)的值 (这里^为乘方,不是异或),2=<k<=16,0<x,y<2000000000,有一半的测试点里 x^y 会溢出int的范围(>=2000000000)

输入描述:

每组测试数据包括一行,x(0<x<2000000000), y(0<y<2000000000), k(2<=k<=16)

输出描述:

输入可能有多组数据,对于每一组数据,root(x^y, k)的值
示例1

输入

4 4 10

输出

4

Description

x y % ( k 1 ) x^y\%(k-1) ,具体推导过程参考> https://blog.qjm253.cn/?p=371
注意当N<y的情况,特殊判定一下。

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
LL binary_pow(LL a, LL b, LL m)
{
    LL ans = 1;
    a = a % m;
    while (b > 0)
    {
        if (b & 1) //等价b%2==1
            ans = ans * a % m;
        a = a * a % m; //令a平方后取模
        b >>= 1;       //等价b=b/2
    }
    return ans;
}
int main()
{
    // freopen("in.txt", "r", stdin);
    LL x, y, k;
    while (~scanf("%lld%lld%lld", &x, &y, &k))
    {
        LL res = binary_pow(x, y, k - 1);
        if (res == 0)
            printf("%lld\n", k - 1);
        else
            printf("%lld\n", res);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sunlanchang/article/details/88559180