gpt4 book ai didi

c - 如何计算c中的逆模幂?

转载 作者:行者123 更新时间:2023-12-01 23:27:06 26 4
gpt4 key购买 nike

我想取整数的模逆(k≥1),然后将结果乘以另一个整数,如以下表达式所示:

result=((x^(-k)))*y mod z

我如何实现这个表达式,其中 k≥1?

最佳答案

你需要定义四个函数:

uint64_t modular_exponentiation(uint64_t x, uint64_t y, uint64_t z) 
{
uint64_t res = 1;
x = x % z;
while (y > 0)
{
if (y & 1)
res = (res*x) % p;
y = y>>1; // y = y/2
x = (x*x) % z;
}
return res;
}

uint64_t moduloMultiplication(uint64_t a, uint64_t b,uint64_t z)
{
uint64_t res = 0;
a %= z;

while (b)
{
if (b & 1)
res = (res + a) % z;

a = (2 * a) % p;
b >>= 1; // b = b / 2
}
return res;
}


void extendedEuclid(uint64_t A, uint64_t B)
{
uint64_t temp;
if(B == 0)
{
d = A;
x = 1;
y = 0;
}
else
{
extendedEuclid(B,A%B);
temp = x;
x = y;
y = temp - (A/B)*y;
}
}

int modInverse(uint64_t A, uint64_t M)
{
extendedEuclid(A,M);
if (x < 0)
x += M;
return (x);
}

ma​​in() 中:

uint64_t result=0x00;
result=modular_exponentiation(x,k,z); // (x^k) mod z
result=modInverse(result,z); // ((x^k)^-1) mod z == x^(-k) mod z
result=moduloMultiplication(result,y,z);// x^(-k) * y mod z

关于c - 如何计算c中的逆模幂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56335032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com