HDU_1061:Rightmost Digit

來源:互聯網
上載者:User

標籤:

Problem DescriptionGiven a positive integer N, you should output the most right digit of N^N. InputThe 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). OutputFor each test case, you should output the rightmost digit of N^N. Sample Input234 Sample Output7 6HintIn 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. 最先想到的是一個一個算,但是由於資料範圍太大,O(n^2)的時間複雜度對於n = 10億時,10億^10億次乘法運算實在是不能忍受的。因此下面的程式逾時(Time Limit Exceeded)。
#include<stdio.h>int main(void){    int cases, n, copy_n, result;    scanf("%d", &cases);    while(cases--)    {        scanf("%d", &n);        copy_n = n;        n = n%10;        result = 1;        while(copy_n--)        {            result = (result*n)%10;        }        printf("%d\n", result);    }        return 0;}

下面,快速冪一來就AC了:

#include<stdio.h>int my_power(int m, int n); // 求m的n次方的尾數int main(void){    int cases, n;    scanf("%d", &cases);    while(cases--)    {        scanf("%d", &n);        printf("%d\n", my_power(n, n));    }        return 0;}int my_power(int m, int n){    m = m%10;    if(n == 1)        return m;    if(n%2 == 0)        return ( my_power(m*m, n/2) ) % 10;    else        return ( my_power(m*m, n/2)*m ) % 10;}

可以看到,快速冪的時間複雜度是O(logn),n = 10億時,大約32次遞迴調用就能出結果,效率極大的提高了。

HDU_1061:Rightmost Digit

聯繫我們

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