快速幂
今天写了一道题
给出一个整数N,输出N^N(N的N次方)的十进制表示的末位数字。
输入
一个数N(1 <= N <= 10^9)
输出
输出N^N的末位数字
输入样例
13
输出样例
3
我提交的代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = n;
int res = 1;
while(n!=0) {
res *=m;
if(res>=10000) {
res %= 10000;
}
n--;
}
res %= 10;
System.out.println(res);
}
}
我当时以为应该很简单的写出来的,但在25个用例中,有三个用例一直时间超限。说明其中有更简便的算法。其实这道题可以找到规律,余数是循环的,但同样可以使用快速幂算法达到我们的目的。
快速幂:
例如我们这道题,可以这样想
可以考虑成根据二进制的权值来求解的。那么在关于位运算的部分,我们可以逐位获取输入值的位,碰到0,就累乘,碰到1,就将累乘的值并且将乘到答案。由此可以得到代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long temp = n;
long res = 1;
while(n!=0) {
if((n&1)==1) {//与(n%2)==1等价
res = (res * temp)%10;
}
temp = (temp *temp)%10;
n = n >> 1;//n/=2
}
System.out.println(res);
}
}