Niukehuahua teaches math month by month (quick power)

Huahua teaches math every month

analysis:

This question belongs to the fast power type. The only tricky thing is that the regular fast power will explode long long. At this time, for C++ that does not have large numbers, either use handwritten large number functions to do it, or just use fast power On the basis, in order to prevent overflow, the multiplication in the fast power is divided into addition for the remainder, similar to the fast multiplication of the fast power.

Code:

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

ll QuickMul(ll a, ll b, ll mod)
{
    
    
	ll base = a, res = 0;
	while (b)
	{
    
    
		if (b % 2)res = (res + base) % mod;
		base = base * 2 % mod;
		b /= 2;
	}
	return res;
}

ll QuickPow(ll a, ll b, ll mod)
{
    
    
	ll base = a, res = 1;
	while (b)
	{
    
    
		if (b % 2)res = QuickMul(res, base, mod);
		base = QuickMul(base, base, mod);
		b /= 2;
	}
	return res;
}

int main()
{
    
    
	int n;
	scanf("%d", &n);
	while (n--)
	{
    
    
		ll a, b, c;
		scanf("%lld%lld%lld", &a, &b, &c);
		printf("%lld\n", QuickPow(a, b, c));
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43700916/article/details/88376088