找规律,建表、查表(1)
#include <bits/stdc++.h>
using namespace std;
int f[10][6] = {{1,0,0},{1,1},{1,2,4,8,6,2},{1,3,9,7,1},{1,4,6,4},
{1,5,5},{1,6,6},{1,7,9,3,1},{1,8,4,2,6,8},{1,9,1}};
int c[10] = {1,1,4,4,2,1,1,4,4,2}; // 最小正周期
int s[10] = {1,0,1,0,1,1,1,0,1,0}; // 循环起点
int main(){
int a, b;
while(scanf("%d %d", &a, &b) == 2){
a %= 10;
b = b < s[a] ? b : (b-s[a])%c[a]+s[a];
printf("%d\n", f[a][b]);
}
return 0;
}
找规律,建表、查表(2)
#include <bits/stdc++.h>
using namespace std;
// int f[10][6] = {{1,0,0,0,0,0},{1,1,1,1,1,1},{1,2,4,8,6,2},{1,3,9,7,1,3},{1,4,6,4,6,4},
// {1,5,5,5,5,5},{1,6,6,6,6,6},{1,7,9,3,1,7},{1,8,4,2,6,8},{1,9,1,9,1,9}};
// int c[10] = {4,4,4,4,4,4,4,4,4,4}; // 最小正周期的最小公倍数——也是周期
// int s[10] = {1,1,1,1,1,1,1,1,1,1}; // 循环起点一致化
int main(){
int a, b, f[6]={1};
while(scanf("%d %d", &a, &b) == 2){
a %= 10;
for(int i = 1; i <= 5; i++) f[i] = f[i-1]*a%10; // 动态建表
b = b < 5 ? b : (b-1)%4+1;
printf("%d\n", f[b]);
}
return 0;
}
快速幂 long long
#include <bits/stdc++.h>
using namespace std;
#define LL long long
int fastPower(LL base, LL power){ // long long
int res = 1;
while(power){
if(power&1) res = res*base%10; // res*base long long
base = base*base%10; // base*base long long
power >>= 1;
}
return res;
}
int main(){
int a, b;
while(scanf("%d %d", &a, &b) == 2){
printf("%d\n", fastPower(a, b));
}
return 0;
}
快速幂 int
#include <bits/stdc++.h>
using namespace std;
int fastPower(int base, int power){
int res = 1;
base %= 10; // 可避免int溢出
while(power){
if(power&1) res = res*base%10;
base = base*base%10;
power >>= 1;
}
return res;
}
int main(){
int a, b;
while(scanf("%d %d", &a, &b) == 2){
printf("%d\n", fastPower(a, b));
}
return 0;
}