How to calculate x^y mod z? [duplicate]

怎甘沉沦 提交于 2019-12-13 07:58:12

问题


I am wondering how to calculate x^y mod z. x and y are very large (can't fit in 64 bit integer) and z will fit 64 bit integer. And one thing don't give answers like x^y mod z is same as (x mod z)^y mod z.


回答1:


Here is the standard method, in pseudo-code:

function powerMod(b, e, m)
    x := 1
    while e > 0
        if e % 2 == 1
            x := (b * x) % m
            e := e - 1
        else
            b := (b * b) % m
            e := e / 2
    return x

The algorithm is known as exponentiation by squaring or the square and multiply method.




回答2:


If you are using Java, then turn x, y, and z into BigInteger.

BigInteger xBI = new BigInteger(x);
BigInteger yBI = new BigInteger(y);
BigInteger zBI = new BigInteger(z);
BigInteger answer = xBI.modPow(yBI,zBI);


来源:https://stackoverflow.com/questions/28138956/how-to-calculate-xy-mod-z

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!