Finding pow(a^b)modN for a range of a's

断了今生、忘了曾经 提交于 2019-12-23 19:48:34

问题


For a given b and N and a range of a say (0...n),

I need to find ans(0...n-1) where,

ans[i] = no of a's for which pow(a, b)modN == i

What I am searching here is a possible repetition in pow(a,b)modN for a range of a, to reduce computation time.

Example:-

if b = 2 N = 3 and n = 5

for a in (0...4):
    A[pow(a,b)modN]++;

so that would be

pow(0,2)mod3 = 0
pow(1,2)mod3 = 1
pow(2,2)mod3 = 1
pow(3,2)mod3 = 0
pow(4,2)mod3 = 1

so the final results would be:

ans[0] = 2 // no of times we have found 0 as answer .

ans[1] = 3

...


回答1:


Your algorithm have a complexity of O(n). Meaning it take a lot of time when n gets bigger.

You could have the same result with an algorithm O(N). As N << n it will reduce your computation time.

Firts, two math facts :

pow(a,b) modulo N == pow (a modulo N,b) modulo N

and

if (i < n modulo N)
   ans[i] = (n div N) + 1
else if (i < N)
   ans[i] = (n div N)
else
   ans[i] = 0

So a solution to your problem is to fill your result array with the following loop :

int nModN = n % N;
int nDivN = n / N;
for (int i = 0; i < N; i++)
{
    if (i < nModN)
        ans[pow(i,b) % N] += nDivN + 1;
    else
        ans[pow(i,b) % N] += nDivN;
}



回答2:


You could calculate pow for primes only, and use pow(a*b,n) == pow(a,n)*pow(b,n).

So if pow(2,2) mod 3 == 1 and pow(3,2) mod 3 == 2, then pow(6,2) mod 3 == 2.



来源:https://stackoverflow.com/questions/18041428/finding-powabmodn-for-a-range-of-as

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