求最大公约数3种方法5个版本

/*求两个数的最大公约数(greatest common divisor)*/

#include <stdio.h>

void swap(int *a, int *b){
	int c = *a;
	*a = *b;
	*b = c;
}

//辗转相除法迭代写法
int GCD_V1(int divident, int divisor){
	int mod;
	while ( (mod = divident % divisor) != 0){
		divident = divisor;
		divisor = mod;
	}
	return divisor;
}

//辗转相除法递归写法
int GCD_V2(int divident, int divisor){
	int mod = divident % divisor;
	if (mod == 0)
		return divisor;
	else
		return GCD_V2(divisor, mod);
}

//相减法迭代写法
int GCD_V3(int minuend, int subtracter){
	if (minuend < subtracter)
		swap(&minuend, &subtracter);

	int different;
	while ( (different = minuend - subtracter) != subtracter){
		minuend = subtracter;
		subtracter = different;
	}
	return different;
}

//相减法递归写法
int GCD_V4(int minuend, int subtracter){
	if (minuend < subtracter)
		swap(&minuend, &subtracter);

	int different = minuend - subtracter;
	if (different == subtracter)
		return different;
	else
		return GCD_V4(subtracter, different);
}

//暴力枚举
int GCD_V5(int one, int another){
	int min = one;
	if (another < min)
		min = another;
	int gcd;
	for (gcd = min; gcd > 0; gcd--)
		if (one % gcd == 0 && another % gcd == 0)
			return gcd;
}

int main(){
	return 0;
}

你可能感兴趣的:(递归,gcd,最大公约数,相减,相除)