Application of dichotomy (fast power)

Insert picture description here
For this problem, using ordinary traversal is a bit inappropriate, the complexity is too high.
Here you can use the fast power method based on the idea of ​​dichotomy, also called dichotomy. as follows:Insert picture description here

typedef long long LL;
//递归的写法
LL BINARYPOW(LL a,LL b,LL m){
	if(b==0) return 1;
	//b为奇数,转换为b-1
	if(b%2==1) return a*binaryPow(a,b-1,m)%m;
	else{
		LL mul=binaryPow(a,b/2,m);
		return mul*mul%m;
	}
}

The condition if (b% 2 == 1) can be replaced with if (b & 1), because b & 1 is located in the operation and judges whether the last bit of b is 1, so when b is odd, b & 1 returns 1, and the if condition holds.

Published 19 original articles · praised 2 · visits 746

Guess you like

Origin blog.csdn.net/zan1763921822/article/details/104280674