求A的B次方的最後三位整數

題目描述
  Now let’s do a real easy problem as warming up . You should calculate the last three digits of A^B (1000000 > A , B > 0) . Is it so easy to you ?
輸入
  There are multiply test cases , each test case include two integers in one line which present A and B , and separated with a single space .
輸出
  In each test case , output the last three digits of A^B .
樣例輸入
  1 1
  2 3
樣例輸出
  1
  8


  很顯然,題目的要求是冪運算,首先想到的是用pow(x,y)函數來求解,但是由於int類型的變量有一定的範圍,所以這種方法可以pass掉。
  剩下的自然是考慮通過連乘的方式來解決,根據題目和實際運算的需要,因爲最後三位整數的值完全可以通過一個大整數的最後三位確定,所以通過取餘簡化計算,而且結果必定是正確的。

附上代碼:

#include<stdio.h>
int main()
{
    int i,x,y,z;
    while(scanf("%d %d",&x,&y) != EOF)
    {
        z = x % 1000;
        for(i = 1; i < y; i++)
        {
            z = z * (x % 1000);
            z %= 1000;
        }
        printf("%d\n",z);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章