2021 Niu Guest Winter Holiday Algorithm Basic Training Camp 6 C. The last three

C. The last three

Title link: https://ac.nowcoder.com/acm/contest/9986/C

Title description:

Niuniu just finished studying the index recently, he understood that 2^2=4, 3^3=27...

However, he now wants to know: What are the last three digits of 5^n?

Enter a description:

There are multiple sets of input data.

Enter a number n for each group of data, which represents the exponent.

Output description:

Output the last three digits of 5^n.

Example 1:

Input
1
3
5
Output
005
125
125
Note:
For 100% data, 0 <= n <= 1e9.

The number of data groups t <= 10^6.

Problem-solving ideas:

Ⅰ. Fast power: Let modulus=1000, and use fast power directly.
Ⅱ. Finding rules: special judgment at n<3, and parity discussion at n>=3.

code show as below:

Ⅰ: Fast power

#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;
}

Ⅱ: Find the law

#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;
}

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/114033111