標籤:
又是一個赤裸裸的模板,倍增思想其實是關鍵,我們只有稍加改動,也可以得出另外一種運算,快速乘,但實用性不如快速冪,大概只有在大整數乘法時才會用到
而倍增思想並不是僅僅用於快速運算,倍增求lca也是常用的倍增演算法
#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>using namespace std;typedef long long ll;ll fast_power(ll,ll,ll); // 求 a^b % c int main(){ ll a,b,c; scanf("%lld%lld%lld",&a,&b,&c); printf("%lld",fast_power(a,b,c)); return 0;}ll fast_power(ll a,ll b,ll c){ ll ans=1; // 倍增思想求快速冪 while (b){ if (b & 1) ans = ans * a % c; else ans %= c; b >>= 1; a = a * a % c; } return ans;}
#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>using namespace std;typedef long long ll;ll fast_calc(ll,ll,ll);int main(){ ll a,b,c; scanf("%lld%lld%lld",&a,&b,&c); printf("%lld",fast_calc(a,b,c)); return 0;}ll fast_calc(ll x,ll y,ll z){ ll ans = 0; while (y){ if (y & 1){ ans += x; ans %= z; } x <<= 1; x %= z; y >>= 1; } return ans;}
OI模板(3)—— 快速冪(fast_power)