Rightmost Digit

xiaoxiao2021-02-28  132

Rightmost Digit

Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)

Total Submission(s) : 32 Accepted Submission(s) : 20

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

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.

解法一:0ms;解法二:15ms;

解法一(找规律):

#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; int main() { long long int n, m, t; cin >> t; while (t--) { cin >> n; int k; m = n % 10; k = m; if (n % 4) n = n % 4; else n = 4; while (--n) { k = (k*m) % 10; //cout << k << endl; } cout << k << endl; } return 0; }

解法二(快速幂)

#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; int main() { long long int n, m, q, t; cin >> t; while (t--) { cin >> n; m = 1;//表示幂次为1的常数部分 q = n;//表示幂的次数 while (q)//快速幂 { if (q % 2) { m = (m*n)%10; } n = (n*n)%10;//n始终表示高次幂部分 q /= 2; } cout << (m*n) % 10 << endl; } return 0; }
转载请注明原文地址: https://www.6miu.com/read-27135.html

最新回复(0)