Daily practice of the Blue Bridge Cup C/C++ B group ~ the same score

Daily practice of the Blue Bridge Cup C/C++ B group ~ the same score

Hello everyone, I am Fei Niao. If the article is helpful to you, please like it, collect it and support the editor, thank you.

Topic description

This question is a fill-in-the-blank question. After calculating the result, use the output statement in the code to output the filled result.

If the greatest common divisor of the numerator and denominator of a fraction is 11, the fraction is called a reduced fraction.

For example, 3/4, 1/8, and 7/1 are all reduced fractions.

Excuse me, how many fractions are there, with both numerators and denominators being integers between 1 and 2020 (including 1 and 2020)?

Answer:2481215


#include<iostream>

using namespace std;

int gcd(int a,int b){
    
    
	//辗转相除法求最大公约数
	return b == 0 ? a:gcd(b,a%b); 
}
int main(){
    
    
	int ans = 0;
	for(int zi = 1;zi <= 2020;zi++){
    
    
		for(int mu = 1;mu <= 2020;mu++){
    
    
			if(gcd(zi,mu) == 1){
    
    
				ans++;
			}
		}
	}
	cout << "ans = " << ans << endl;
	return 0;
} 

Code idea:

The reduced fraction declaration ans is initialized to 0, the numerator and denominator are for loop, gcd(zi, mu) finds the greatest common divisor of 1, and the reduced fraction plus 1.

int main(){
    
    
	int ans = 0;
	for(int zi = 1;zi <= 2020;zi++){
    
    
		for(int mu = 1;mu <= 2020;mu++){
    
    
			if(gcd(zi,mu) == 1){
    
    
				ans++;
			}
		}
	}
	cout << "ans = " << ans << endl;
	return 0;
} 

The method of tossing and turning, if b is 0, return a, otherwise return gcd, then b is equal to 0, which is equivalent to the remainder of a and b is equal to 0, and a returns the previous b value. You can memorize it as a formula.

int gcd(int a,int b){
    
    
	//辗转相除法求最大公约数
	return b == 0 ? a:gcd(b,a%b); 
}

Guess you like

Origin blog.csdn.net/A6_107/article/details/123005398