GDUFE-OJ 1203 快速冪

來源:互聯網
上載者:User

標籤:時間複雜度   unsigned   class   esc   amp   運算   範圍   tip   二進位   

嘿嘿今天學了快速冪也~~

Problem Description:
   求x的y次方的最後三位元 。  
Input:
一個兩位元x和一個兩位元y。
Output:
輸出x的y次方的後三位元。
Sample Input:
13 13
Sample Output:
253
思路:快速冪求a^b,然後mod c。因為是隨便輸入的a,b,所以範圍很大,而題目只需求最後三位,所以百位以上的計算不用理了,直接%1000。
 1 #include <stdio.h> 2 int main() 3 { 4     unsigned long long a,b; 5     while(scanf("%llu%llu",&a,&b)!=EOF) 6     { 7         unsigned long long c=1,d=a; 8         while(b!=0) 9         {10         if(b&1!=0)//如果是0則無需計算,因為n*1=n11             c*=d%1000;12             d*=d%1000;13             b>>=1;14         }15         if(c%1000>99)16         printf("%llu\n",c%1000);17         else if(c%1000>9)18         printf("0%llu\n",c%1000);19         else20         printf("00%llu\n",c%1000);21     }22     return 0;23 }

 Tip:以上mod c是因為怕數字過大爆了,一是因為a的b次mod c,二是因為早晚要mod c,所以早mod 無所謂。

小知識:

      快速冪原理:a^b,將b拆成位元相加的形式,從而使運算次數減少

Example:a^11=a^(2^0+2^1+2^3),時間複雜度為O(log11)。

 1 scanf("%d%d",&a,&b) 2         int c=1,d=a; 3         while(b!=0) 4         { 5         if(b&1!=0)//取b的位元的最後一位(相當於b%2!=0)
6 c*=d;
7
d*=d; //每往右推一位,d倍增,2^0 2^1 2^2……
8
b>>=1;//將b的位元往右推一位(相當於b/=2)
9 }
10 printf("%d\n",c);//c=a^b

 

GDUFE-OJ 1203 快速冪

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.