Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
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
给T个测试数据,每一个测试数据会给一个正整数N,求N^N%10。
注意这道题N的范围很大(1<=N<=1,000,000,000),用朴素方法应该会超时,
时间复杂度为O(N),即N为多少,就乘自身多少次。
快速幂
这里要引入快速幂,字面意思,快速求幂,快速幂主要应用了二进制的思想,举个栗子,25,把5转换为二进制,即101,二进制存在着权值,101可转换为(4+0+1),25=2(4+0+1)=24*21
C模板
#include <stdio.h>
#pragma warning(disable:4996)
long long quickpow(long long a,long long b) //计算a^b
{
long long res=1,base=a; //res代表最终答案,base用来模拟二进制权值的变化
for(;b;b>>=1)
{
if(b&1)
res*=base;
base*=base;
}
return res;
}
int main(void)
{
long long a,b;
scanf("%lld %lld",&a,&b);
printf("%lld",quickpow(a,b));
return 0;
}
回到题上来,结果要求%10,有公式(ab)%c=(a%c)(b%c)%c,那么所有问题就解决了,上AC代码
C
#include <stdio.h>
#pragma warning(disable:4996)
long long quickpow(long long a,long long b,long long p)
{
long long res=1%p,base=b;
for(;b;b>>=1)
{
if(b&1)
res=res*base%p;
base=base*base%p;
}
return res;
}
int main(void)
{
int N;
long long a;
scanf("%d",&N);
while(N--)
{
scanf("%lld",&a);
printf("%lld\n",quickpow(a,a,10));
}
return 0;
}
本文介绍了一种高效算法——快速幂,用于解决大整数N的N次方对10取模的问题。通过二进制思想优化传统幂运算,实现O(logN)的时间复杂度。文章提供了C语言实现的代码示例。
400

被折叠的 条评论
为什么被折叠?



