Raising large number to large power and mod it by a large number?

强颜欢笑 提交于 2019-12-03 01:00:48

问题


I am stuck with probably simple question. I got 3 large numbers(A,B,C), all integers and i need to do the following: power A to B and modulo the result by C, and then check if the result is equal to 1. Here's my code:

double power = fmod((pow((double)A,(double)B)),(double)C);
    if (power != 1){
        printf("Something!\n");
    }

And it doesnt work(I tried small numbers, like 17 powered by 28 and moduled by 29). Any suggestions on that?


回答1:


Try this (in order to avoid arithmetic overflow):

unsigned long long power = 1;
A %= C;
while (B > 0)
{
    power = (power * A) % C;
    B--;
}

You can further improve the runtime performance with this:

unsigned long long power = 1;
A %= C;
while (B > 0)
{
    if (B & 1)
        power = (power * A) % C;
    B >>= 1;
    A = (A * A) % C;
}



回答2:


The min and max sizes for Double are -1.7*10^308 and 1.7*10^308 respectively. If you need bigger you could try long long.

Not sure why you are using fmod. But this should do what you want.

double power = ( pow(A, B) ) % C;
if (power != 1){
        printf("Something!\n");
    }



回答3:


try this approach

double a,b,c;

a = 1124124124254234;
b = 1124124124254234 * 5;
c = 1124124124254234 * 2;

double power = pow(a,b); 

double mod = fmod(power, c);

if (mod != 1){
    printf("Something!\n");
}


来源:https://stackoverflow.com/questions/27153665/raising-large-number-to-large-power-and-mod-it-by-a-large-number

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