HDU4506之快速幂取模理解

来源:互联网 发布:大数据调研报告 编辑:程序博客网 时间:2024/06/05 05:14

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=107165#problem/B


第一次接触快速幂,看了别人的博客,x代表底数,n为指数

  1. typedef long long LL;  
  2. LL fun(LL x,LL n,)  
  3. {  
  4.     LL res=1;  
  5.     while(n>0)  
  6.     {  
  7.         if(n & 1)  
  8.             res=(res*x)%Max;  
  9.         x=(x*x)%Max;  
  10.         n >>= 1;  
  11.     }  
  12.     return res;  
  13. }  
大概就是这么个过程,于是我拿2 ^ 5做了一下模拟,if(n & 1)这句就误解了,以为是n == 1后来才知道这句的意思最后一位是否为1,换句话说是判断n是否为奇数,那么就更好理解了,每一次循环如果n为奇数那么>> 1 (相当于 n /= 2)的时候会少乘一次x,这样对快速幂是不是有了更好的理解呢!


好吧,贴个代码

#include <iostream>#include <cstdio>#include <vector>#include <algorithm>const int  MO =  1000000007;#define maxn  10010typedef long long ll;ll aa[maxn];using namespace std;ll quick(ll m,ll n){    ll ans = 1;    while (n)    {        if (n & 1)            ans = (ans*m) % MO;                m = (m * m) % MO;        n >>= 2;  // 就是 n /= 2;    }    return ans;}int main(){    int T;    while (~scanf("%d",&T))    {        while (T--)        {            ll n,t,k,si,so;            scanf("%I64d %I64d %I64d",&n,&t,&k);            for (int i = 0;i < n;i++)                scanf("%I64d",&aa[i]);            si = t % n;            so = quick(k,t);            for (int i = 0;i < n;i++)
//循环数组取模。。。自己模拟一下即可                printf("%I64d%c",aa[(i - si + n) % n] * so % MO,(i == n-1 )?'\n':' ');        }    }    return 0;}


0 0
原创粉丝点击