Fast power calculation (simple calculator)

enter

Enter n in the first line, indicating that you will enter n groups next;

In the next n lines, there are three respectively, a, b, s, which respectively represent the two numbers to be operated, and the operation symbol, such as 1 2 +, which means 1+2, 2 1000000000 ^, which means 2 to the power of 1000000000;

Because the result may be very large, it must be modulo 1000000007 and then output;

Output

Output calculation results, separated by newlines;

C++ code

#include<iostream>
#define ll long long
using namespace std;
ll p = 1000000007;
ll quickpow(ll a, ll b) {
	ll ans = 1;
	while (b) { 
		if (b & 1) ans = ans * a % p;
		a = a * a % p, b = b >> 1;
	}return ans % p;
}

int main() {
	int i;
	cin >> i;
	while (i) {
		ll a, b;
		char s;
		cin >> a >> b >> s;
		if (s == '+') cout << (a % p + b % p) % p << endl;
		if (s == '-') cout << (a % p - b % p) % p << endl;
		if (s == '*') cout << ((a % p) * (b % p)) % p << endl;
		if (s == '^') cout << quickpow(a, b) << endl;
		i--;
	}return 0;
}


The important thing here is the exponentiation operation. If it is in accordance with the conventional method, exponentiation is to continuously multiply itself. The complexity is O(n). Through fast exponentiation, the complexity is reduced to logarithmic level.

The key here is the shift operation of exponent b, b=b>>1, which is to move the binary b to the right by one bit. For example, 2 is the 11th power, 11 is the binary 1011, and 2 is 11 The power is the 1011 power of the binary of 2 and the (8+2+1) power of 2, where 8, 2, 1 is the number of the binary position. According to the power exponent algorithm, 2^(11)= 2^(8+2+1)=2^8*2^2*2^1, there is a pattern between the multiplied numbers, and they are all squares of the previous digit, as long as the number is 1 in the binary digit, here It is necessary to multiply by the corresponding number. Each time it is multiplied, the binary b moves one bit to the right. When b moves to the right to 0, it exits and the product ends. This is the mathematical principle of fast exponentiation.

 

Guess you like

Origin blog.csdn.net/sinat_39416814/article/details/108700773