Skip to content

pow_mod で x が大きいとオーバーフローする #33

@m1zz1y

Description

@m1zz1y

Kotlin版へ移植( https://github.com/da-louis/ac-library-kt/pull/33 )してもらっている際に発見

xが大きいと30行目のx*xでオーバーフローしてしまうようなので、先にmodを取っておく必要がありそうです。
(もしくは第一引数はint型が正しい?)

public static long pow_mod(long x, long n, long m){
assert(n >= 0 && m >= 1);
long ans = 1;
while(n > 0){
if(n%2==1) ans = (ans * x) % m;
x = (x*x) % m;
n /= 2;
}
return ans;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions