Number theory-fast multiplication (template)

Fast multiplication purpose: calculate a*b%mod, and a*b is greater than long long.

Basic principle: The speed of calculation and addition in a computer is often much faster than that of multiplication, and fast multiplication is to decompose a*b into polynomials and add them through the distributive law of multiplication.

Take a date: 20*13, convert 13 into binary 1101, then it is 20*2^0+20*2^2+20*2^3. (Similar to fast power)

ll quick_mulitiply(ll a,ll b,ll mod) {
	ll res=0;
	while(b) {
		if(b&1) res=(res+a)%mod;
		a=(a+a)%mod;
		b>>=1;
	}
	return res;
}

 

Guess you like

Origin blog.csdn.net/qq_44132777/article/details/109664812