C.末三位
题目链接:https://ac.nowcoder.com/acm/contest/9986/C
题目描述:
牛牛最近刚学完指数,他理解了2^2=4 ,3^3=27 ……
但是,他现在想知道:5^n的末三位是多少?
输入描述:
有多组输入数据。
每组数据输入一个数n,表示指数。
输出描述:
输出5^n的末三位。
示例1:
输入
1
3
5
输出
005
125
125
备注:
对于100%的数据,0 <= n <= 1e9。
数据组数 t <= 10^6。
解题思路:
Ⅰ.快速幂:令模数=1000,直接用快速幂。
Ⅱ.找规律:n<3时特判,n>=3时分奇偶性讨论。
代码如下:
Ⅰ:快速幂
#include <iostream>
using namespace std;
int qsm(int a,int b,int c){
int res=1;
while(b){
if(b&1)
res=(res*a)%c;
a=(a*a)%c;
b>>=1;
}
return res;
}
int main() {
int n;
while(cin>>n){
int ans=qsm(5,n,1000);
printf("%03d\n",ans);
}
return 0;
}
Ⅱ:找规律
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
if (n==0) cout<<"001"<<endl;
else if (n==1) cout<<"005"<<endl;
else if (n==2) cout<<"025"<<endl;
else if (n%2==1)cout<<"125"<<endl;
else cout<<"625"<<endl;
}
return 0;
}