最大公約數

重要性質:gcd(a,b)=gcd(b,a) ( 交換律
gcd(-a,b)=gcd(a,b)
gcd(a,a)=|a|
gcd(a,0)=|a|
gcd(a,1)=1
gcd(a,b)=gcd(b, a mod b)
gcd(a,b)=gcd(b, a-b)
1. 注意0 的狀況

2. 注意負數的狀況 java

public class GCD {

	
	//展轉相除法
	public static int gcd1(int a, int b){
		
		a = Math.abs(a);
		b = Math.abs(b);
		int temp = 0;
		if (a < b){
			temp = b;
			b = a;
			a = temp;
		}
		
		while (b != 0){
			
			temp = b;
			b = a % b;
			a = temp;
		
		}
		return a;
	}
	
	//更相減損術
	public static int gcd2 (int a, int b){
		
		if (a == b){
			return Math.abs(a);
		}
		a = Math.abs(a);
		b = Math.abs(b);
		int temp = 0;
		// a 取較大值
		a = a < b ? b : a;
		
		while (b != 0){
			temp = a - b;
			a = Math.max(b, temp);
			b = Math.min(b, temp);
		}
		return a;
	}
	
	//遞歸
	public static int gcd3 (int a, int b){
		
		if (a == 0 && b != 0){
			return Math.abs(b);
		} else if (a != 0 && b == 0){
			return Math.abs(a);
		} else if (a == 0 && b == 0){
			return a;
		}
		
		a = Math.abs(a);
		b = Math.abs(b);
		if (a % b == 0){
			return b;
		} else {
			return gcd3(b, a % b);
		}
		
	}
	//最小公倍數
	public static int lcm (int a, int b){
		if (a == 0 || b == 0){
			return 0;
		}
		return a * b / gcd1(a, b);
	}
	public static void main(String[] args) {
		gcd1(-1,0);
		System.out.println(gcd2(4,2));
		System.out.println(gcd3(-1,0));
	}
}
相關文章
相關標籤/搜索