1. 程式人生 > >ACM刷題之HDU————Rightmost Digit

ACM刷題之HDU————Rightmost Digit

Rightmost Digit

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8142 Accepted Submission(s): 2078
Problem Description Given a positive integer N, you should output the most right digit of N^N.
Input The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
Output For each test case, you should output the rightmost digit of N^N.
Sample Input
2
3
4
Sample Output
7
6

Hint In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7. In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.
—————————————————————————————————————————————————————————————————————————————

乍一看,好像很簡單的樣子,迴圈後取餘就好了。

下面是我最開始的錯誤程式碼:

#include<stdio.h>
int main()
{
int num,a,b,zu,i;
scanf("%d",&zu);
while(zu--){
scanf("%d",&a);
b=a;
for(i=1;i<b;i++){
a=(a*b)%10;
}
printf("%d\n",a);
}
return 0;
} 


看起來好像挺好的,運算的結果也都是對的。

然而提交的時候會顯示超時。

據說要用快速冪取模運演算法。這個方法我還沒來得及去百度研究下(懶。。

這題還有簡便的方法,就是他們相乘是迴圈的,4次一迴圈。

觀察題目後易知,結果的最右邊數其實只和個位有關。於是我們單獨拉出個位來看看。

—————————————————————————————————————————————————————————————————————————————

下面是各個數字的迴圈情況

00 000

11 111

24 862

39 713

46 466

555 55

666 66

79 317

84 268

91 919

—————————————————————————————————————————————————————————————————————————————

我們發現,大部分都是4次一迴圈,紅色標註的都是不變的。有了這個規律後,經過除錯,最後我寫了這個程式碼。

#include<stdio.h>
int main()
{
    int a,b,num,zu,b2,c,i,b3;
    scanf("%d",&zu);
    while(zu--){
        scanf("%d",&a);
        b2=a;
        b=a%10;
        b3=b;
        if(b==0||b==1||b==5||b==6) {
            printf("%d\n",b);
            continue;
            }
        if(a<10){
            for(i=1;i<b2;i++){
                 a=(a*(b2))%10;
                 }
            printf("%d\n",a);
            continue;
            }
        c=a%4;
        c=c+3;
        for(i=1;i<=c;i++)
            b=b3*b;
        printf("%d\n",b%10);
    }
}


一些具體細節就暫時不寫了。。等我自學完快速冪取模再回來填坑吧得意

感謝HSS一直以來對我提供的幫助大笑

昨天晚上開完ACM的會議,發現任重道遠,回到寢室後一直在刷題。第一次用杭電的OJ系統來刷題(之前一直用的是南洋理工學院的,隊裡有一個人也和我一樣用這個2333)
刷的steps 在第二章遇到這樣一題,原先很快的就編好了,但是提交的時候一直都在提示超時。後來問了基友(以後不特別說明的話,基友就是HSS。。)這題他大一上的時候也遇到過,當時也是被卡住過。

————————————寫於2016-3-24

寢室·夜