Algorithm C/C++ : Fastest way to compute (2^n)%d with a n and d 32 or 64 bit integers

时间:2021-11-02 01:55:46

I am searching for an algorithm that allow me to compute (2^n)%d with n and d 32 or 64 bits integers.

我正在寻找一种算法,允许我用n和d 32或64位整数计算(2 ^ n)%d。

The problem is that it's impossible to store 2^n in memory even with multiprecision libraries, but maybe there exist a trick to compute (2^n)%d only using 32 or 64 bits integers.

问题是即使使用多精度库也不可能将2 ^ n存储在内存中,但是可能存在仅使用32或64位整数来计算(2 ^ n)%d的技巧。

Thank you very much.

非常感谢你。

1 个解决方案

#1


24  

Take a look at the Modular Exponentiation algorithm.

看一下Modular Exponentiation算法。

The idea is not to compute 2^n. Instead, you reduce modulus d multiple times while you are powering up. That keeps the number small.

这个想法不是计算2 ^ n。相反,您在通电时会多次减少模数d。这使数字变小。

Combine the method with Exponentiation by Squaring, and you can compute (2^n)%d in only O(log(n)) steps.

将该方法与Squaring的Exponentiation相结合,您只需在O(log(n))步骤中计算(2 ^ n)%d。

Here's a small example: 2^130 % 123 = 40

这是一个小例子:2 ^ 130%123 = 40

2^1   % 123 = 2
2^2   % 123 = 2^2      % 123    = 4
2^4   % 123 = 4^2      % 123    = 16
2^8   % 123 = 16^2     % 123    = 10
2^16  % 123 = 10^2     % 123    = 100
2^32  % 123 = 100^2    % 123    = 37
2^65  % 123 = 37^2 * 2 % 123    = 32
2^130 % 123 = 32^2     % 123    = 40

#1


24  

Take a look at the Modular Exponentiation algorithm.

看一下Modular Exponentiation算法。

The idea is not to compute 2^n. Instead, you reduce modulus d multiple times while you are powering up. That keeps the number small.

这个想法不是计算2 ^ n。相反,您在通电时会多次减少模数d。这使数字变小。

Combine the method with Exponentiation by Squaring, and you can compute (2^n)%d in only O(log(n)) steps.

将该方法与Squaring的Exponentiation相结合,您只需在O(log(n))步骤中计算(2 ^ n)%d。

Here's a small example: 2^130 % 123 = 40

这是一个小例子:2 ^ 130%123 = 40

2^1   % 123 = 2
2^2   % 123 = 2^2      % 123    = 4
2^4   % 123 = 4^2      % 123    = 16
2^8   % 123 = 16^2     % 123    = 10
2^16  % 123 = 10^2     % 123    = 100
2^32  % 123 = 100^2    % 123    = 37
2^65  % 123 = 37^2 * 2 % 123    = 32
2^130 % 123 = 32^2     % 123    = 40