Fast power (C language)

Foreword
The fast power algorithm is generally used in high-order power modulo questions, such as finding 3 raised to the 10000th power modulo 7. At this time, some students will say: Isn’t this simple? Should I call the pow function directly and do nothing with the result %7? But can a number as huge as 3 raised to the power of 10,000 really be stored in a computer? Obviously it won't work, you will only get a wrong number, so how can we get the answer? First we need to know the algorithm of modulus.
( a * b ) % c = ( ( a % c ) * ( b % c ) ) % c (If you don’t know why, please Baidu yourself)
After understanding the algorithm of modulus, let us get to the main topic today!
Insert image description here
Fast power
Now that we know the algorithm of modulus, then 3 to the power of 10,000%7 is converted into (((3%7)*3 )%7)*3)%7…
In this way, the number will not be too large and out of range. This can be achieved using a loop method.

#include<stdio.h>
int main()
{
    
    
	int a = 3, b = 10000;
	int ans = 1;
	while (b--)
	{
    
    
		ans = ans * a % 7;
	}
	printf("%d\n", ans);
	return 0;
}

But this requires 10,000 cycles, which is very inefficient. At this time, we need to use our fast power algorithm.
First, 3 to the power of 10,000 = 9 to the power of 5,000 = 81 to the power of 2,500... and so on. If we square the base, then we just divide the power by 2. This can greatly improve efficiency, but we must pay attention to special situations. For example, 3 to the power of 10001 is not an even number at this time, but we can turn it into an even number, or 3*3 to the power of 10,000, that is It is said that we must consider the odd and even cases of powers when performing fast power arithmetic.
I will show you the code below.

#include<stdio.h>
int main()
{
    
    
	int a = 3, b = 10000;
	int ans = 1;
	while (b)//当b大于0时进行循环
	{
    
    
		if (b%2==1)
			ans = ans*a%7;
		b /= 2;
		a = a*a%7;
	}
	printf("%d", ans);
	return 0;
}

So is there a faster way? Of course, we know that using bit operators and shift operators is much faster than using / and %. Then we can make such modifications to the code.

#include<stdio.h>
int main()
{
    
    
	int a = 3, b = 10000;
	int ans = 1;
	while (b)
	{
    
    
		if (1 & b)//若果1&b=1说明b是奇数,如果1&b=0说明b是偶数
			ans = ans*a%7;
		b >>= 1;//相当于b=b/2
		a = a*a%7;
	}
	printf("%d", ans);
	return 0;
}

This is the fast power algorithm. If you think the blogger is good at what he said, please give the blogger a like to support it~ (It would be better if you can add it to your favorites). So that’s it for today’s sharing. See you in the next issue!

Guess you like

Origin blog.csdn.net/Tokai___Teio/article/details/134891564