C - A magical problem of number theory

开局一条鲲_

2021-07-20 21:08:50

Personal

 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.

思路:本题只看最后一位数即可,最后一位数在不断相乘的过程中会出现循环,所以根据n的最后一位数,以及最后一位数的循环次数,直接打表就可以了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

int t;
long long n; 

int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld",&n);
        long long k=n;
        n%=10;
        if(n==1 || n==5 || n==6 || n==0) printf("%lld\n",n);
        else if(n==2 || n==3 || n==7 || n==8)
        {
            k%=4;
            if(n==2)
            {
                if(k==0) printf("6\n");
                if(k==1) printf("2\n");
                if(k==2) printf("4\n");
                if(k==3) printf("8\n");
            }
            else if(n==3)
            {
                if(k==0) printf("1\n");
                if(k==1) printf("3\n");
                if(k==2) printf("9\n");
                if(k==3) printf("7\n");
            }
            else if(n==7)
            {
                if(k==0) printf("1\n");
                if(k==1) printf("7\n");
                if(k==2) printf("9\n");
                if(k==3) printf("3\n");
            }
            else 
            {
                if(k==0) printf("6\n");
                if(k==1) printf("8\n");
                if(k==2) printf("4\n");
                if(k==3) printf("2\n");
            }
        }
        else if(n==9 || n==4)
        {
            k%=2;
            if(n==9)
            {
                if(k==0) printf("1\n");
                if(k==1) printf("9\n");
            }
            else
            {
                if(k==0) printf("6\n");
                if(k==1) printf("4\n");
            }
        }
    }
    return 0;
}