Learning diary number five - Quick power modulo

Number Theory learning diary

 

Ah ...... Long time no update number theory, and recently there watching, but there are still a lot of number theory Niubi point do not understand (or too dishes), it is still slowly come step by step, then record it quickly today to take power modulus algorithm it.

 

Fast modulo exponentiation is when we want to calculate the 64% 5 3 ^, 4 ^ 3 16% A method of this type a ^ b% c when the need to use large numbers of similar.

 

First of all, for some relatively small data such as 2 ^ 3,3 ^ 2 which of course do not need the power of fast modulo even larger point of time, we can solve the violence problem, you can use long long, but sometimes special data huge, we need to do some processing, we know little of it is easy to work out, so what we need is to put big data into small data to count. So how do you go to big data into small data it?

 

First with the basic code is calculated to look at this pattern:

#include<iostream>
#include<conio.h>

long long FPM( long long a, long long b,long long c)
{
    long long sum = 1;
    a = a % c;
    for (int i = 1; i < b; i++)
    {
        sum = (sum * a)%c;
    }
    return sum;
}

int main(int argc, const char * argv[])
{
    long long a, b, c;
    std::cin >> a >> b >> c;
    std::cout << FPM(a, b, c);
    _getch();
    return 0;
}

This algorithm is slightly larger number, we can directly reduce the size of a then multiplied modulo continue, the answer, but if b is large enough, and a large enough, this approach also will burst stack.

 

Therefore, we need to optimize this, if we want to reduce the size of b, such as 64 ^ 5 ^ 32 we can become 25, then along this idea, we go parity judgment, if it is odd, we just need to an extract of a line, assuming that b is odd, we can become a * (a ^ 2) ^ (b / 2), optimized code:

 

#include<iostream>
#include<conio.h>

long long FPM( long long a, long long b,long long c)
{
    long long sum = 1;

    while(b) {
        if (b & 1) {
            sum = (sum * a) % c;
            b--;
        }
            b >>= 1;
            a = (a * a) % c;
        
    }

    return sum;
}

int main(int argc, const char * argv[])
{
    long long a, b, c;
    std::cin >> a >> b >> c;
    std::cout << FPM(a, b, c);
    _getch();
    return 0;
}

 

As shown in the code, the parity judgment into the first cycle, if the sum is odd let * a, then b / 2, the result of a constant modulo, b will equal 1 and finally, let the sum to obtain the final value, return sum.

 

The above is a simple and fast algorithm modulo the power.

--------------------------------------------------------------------

Guess you like

Origin www.cnblogs.com/xiangqi/p/11302947.html