C 中的模幂运算

Modular exponentation in C

求助!我需要实现一个 C 程序(仅使用字符串、stdlib 和 stdio 库),它使用非常大的数字的模幂,其中一些是 260 位数字。我正在考虑使用链表,但找不到关于如何实现的好参考 it.I 需要这个,因为我需要使用 RSA 来加密和解密消息。

此外,我在获取两个非常大的数字的 GCD 时遇到了完全相同的问题。有什么办法可以做到这一点?

How to store large numbers? 您可以使用这种类型的存储数据 一个可以帮助您使用少量内存并且操作将比其他任何方法都快得多,因为您可以直接在位上制作它们并且您可以使用特殊公式: 对于 add Irecomand 你检查溢出 ;

乘以 (x=x*y):

aux=x;x=0;
while(y)
{ 
  if(last_bit(y)==1)
     x=x+aux;
  shift_left(aux);
  shift_right(y);
}

function modular_pow(base, exponent, modulus)
{
if modulus = 1 then return 0
Assert :: (modulus - 1) * (modulus - 1) does not overflow base
result = 1
base = base mod modulus
while exponent > 0
    if (last_bit(exponent)==1):
       result = (result * base) mod modulus
    exponent = exponent >> 1
    base = (base * base) mod modulus
return result
}