首页 > Web开发 > 详细

杭电 1061 Rightmost Digit计算N^N次方的最后一位

时间:2019-02-26 17:33:47      阅读:485      评论:0      收藏:0      [点我收藏+]
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.

  

我写的错误???错误的原因是超时,

技术分享图片
//rightmost digit
#include<iostream>
using namespace std;
int main()
{
    int n,tmp,m;
    cin>>n;
        while(n--){
        cin>>m;
        tmp=1;
        m%=10;
//        cout<<"m-==="<<m<<endl;
        for(int i=0;i<m;i++)
        tmp=tmp*m%10;
        cout<<tmp<<endl;
        }
    }
View Code

正确代码:

技术分享图片
#include<iostream>
using namespace std;
int main()
{
    int a,ans,n=0;
    double dval = 0;
    int count=0;
    cin>>n;
    while(n--)
    {
        cin>>a;
        ans=1;
        count=a;
        a = a%10;
        while (count)
        {
            if (count&1==1)
                ans=(ans*a)%10;
            a=(a*a)%10;
            count>>=1;
        }
        cout<<ans<<endl;
    }
    return 0;
}
View Code
技术分享图片
#include<iostream>
using namespace std;
int main()
{
    int a,ans,n=0;
    double dval = 0;
    int count=0;
    cin>>n;
    while(n--)
    {
        cin>>a;
        ans=1;
        count=a;
        a = a%10;
        while (count)
        {
            if (count&1==1)
                ans=(ans*a)%10;
            a=(a*a)%10;
            count>>=1;
        }
        cout<<ans<<endl;
    }
    return 0;
}
View Code

 

杭电 1061 Rightmost Digit计算N^N次方的最后一位

原文:https://www.cnblogs.com/helloworld2019/p/10434470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!