Rightmost Digit 1.2.4

来源:互联网 发布:ajax过程 js 编辑:程序博客网 时间:2024/06/06 09:19
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
234
 
Sample Output
76
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 <iostream>
#include <cstdio>
using namespace std;
int a[10][6]={0};
int main()
{
    for(int i=0;i<10;i++){
        int k=1;
        a[i][k]=i;
        int right,tp=i;
        while((right=(tp*i)%10)!=i){
            a[i][++k]=right;
            tp*=i;
        }
        a[i][0]=k;
    }               //打表看一下数组内容
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        int N;
        scanf("%d",&N);
        int r=N%10,q=((N-1)%a[r][0])+1;         //这个q=((n-1)%a[r][0])
        int ans=a[N%10][q];
        printf("%d\n",ans);
    }
    return 0;
}

这里讨论一下q不同的取余的得到的不同结果
首先是取值范围,q=N%n ,那取值范围只与n有关,为[0,n-1]
通过令q+1可以得到【1,n】的范围
一开始我也这样想,但是在本题上不能行,
这样余数为0的就变成了1,3%4得到4;
而我要的是3%4=3,4%4=4,12%4=4;
所以可以用q=N%n,再if(q==0) q=n;
或者用q=(N-1)%n+1
 

0 0
原创粉丝点击