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

前端 未结 3 516
别跟我提以往
别跟我提以往 2021-01-29 11:23

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 t

相关标签:
3条回答
  • 2021-01-29 11:50

    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");
    }
    
    0 讨论(0)
  • 2021-01-29 11:58

    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");
        }
    
    0 讨论(0)
  • 2021-01-29 12:06

    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;
    }
    
    0 讨论(0)
提交回复
热议问题