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

余生长醉 提交于 2019-12-12 07:49:42

问题


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

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.

Thank you very much.


回答1:


Take a look at the Modular Exponentiation algorithm.

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.

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

Here's a small example: 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


来源:https://stackoverflow.com/questions/8963686/algorithm-c-c-fastest-way-to-compute-2nd-with-a-n-and-d-32-or-64-bit-int

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