大数指数运算的题 如何写

img

后面的数据是
in
419725568 322265835
out
271462017

输入x y
输出x^y mod 998244353

请问怎么写才不超时?

long long powerofn(long long x, long long y) {
    long long result = 1;
    while (y > 0) {
        if (y % 2 == 1) {
            result = result * x;
            result = result % 998244353;
        }
        x = x * x;
        x = x % 998244353;
        y = y / 2;
    }
    return result;
}
int main(){
  auto ans=powerofn(419725568 ,322265835);
 cout<<ans<<endl;
}

简单高精度就行了。
代码如下:

#include <iostream>
using namespace std;
long long res(long long base,long long top){
    if(top==0) return 1;//0次幂 
    if(top==1) return base;//1次幂 
    if(top%2) return base*res(base*base,top/2);//奇数次幂 
    else return res(base*base,top/2);//偶数次幂 
}
int main(){
    long long base,top;//底数和指数 
    cin>>base>>top;
    cout<<res(base,top)%998244353;
}

望采纳。