OI模板(3)—— 快速冪(fast_power)

來源:互聯網
上載者:User

標籤:

又是一個赤裸裸的模板,倍增思想其實是關鍵,我們只有稍加改動,也可以得出另外一種運算,快速乘,但實用性不如快速冪,大概只有在大整數乘法時才會用到

而倍增思想並不是僅僅用於快速運算,倍增求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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.