求两个数最大公约数

方法1:欧几里得(辗转相除法):


#include<stdio.h>
#include<string.h>
int f(int a,int b){
	int temp;
	int t;
	if(a<b){

		t=a;
		a=b;
		b=t;}
	else if(a=b) return a;	

		do{
        temp=a%b;
        if(temp==0) return b;
		a=b;
		b=temp;
		}while(temp!=0);

	return b;
	 
	} 
		
	
int main(){
	int x,y;
	
	scanf("%d %d",&x,&y);
	int result=f(x,y);
		printf("%d",result);
     
	

}


image

欧几里得gcd()递归调用法
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <bits/stdc++.h>
int gcd(int a,int b){
	if(b==0)
		return a;
    else 
        return gcd(b,a%b);
}
using namespace std;
int main(){
	int ans=0;
  for(int i=1;i<=2020;i++){
  	for(int j=1;j<=2020;j++){
  		if(gcd(i,j)==1)
  		    ans++;
	  }
  }
  cout<<ans<<endl;

方法2:更相减损法:

#include <stdio.h>
int main()
{ 
	int a;
	int b;
	scanf("%d %d",&a,&b);
	while(a!=b){
	if(a>b) a=a-b;
	else if(a<b) b=b-a;
	}
	printf("%d",a);
	 return 0;
}

image

posted @ 2022-11-09 23:28  Selina风乎舞雩  阅读(29)  评论(0)    收藏  举报