c++简单题(关于数据太大而超时),跪求高手详细解答

来源:百度知道 编辑:UC知道 时间:2024/09/23 10:40:22
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.

#include<iostream>
using namespace std;
int main()
{
int c,n,i,t;
cin>>c;
while(c--)
{
cin>>n;
t=1;
for(i=1;i<=n;i++)
t*=n;
t=t%10;
cout<<t<<endl;
}
return 0;
}

N最大10亿啊, 你要是这么朴素的O(N)必然超时啊. 求最右一位, 那就取N % 10, 也就是N的最右一位的N次方就行了. 这个数字的最右一位是循环的, 找找规律就行了, 很好做.

从你的代码中没有看出来哪里会超时。

t*=n;

改为

t=(t*=n%10)%10;

不懂hi我

用高精度啊