How to find the greatest common divisor?

1. Find the divisor between 1 ~ m / 2, the final divisor is the greatest common divisor

public class Case25_GreatestCommonDivisor{
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("请输入两个正整数:");
		int m = in.nextInt();
		int n = in.nextInt();
		
		int gcd = 1;
		if(m>n)		//交换,确保m为较小者
		{
			m = m^n;
			n = m^n;
			m = m^n;
		}
		if(m == n || n%m == 0)
		{
			System.out.printf("%d与%d的最大公约数是%d\n",m,n,m);
			System.exit(0);
		}
		//找约数,最后的即最大公约数
		for(int i = 1; i <= m/2; i++)
			if(m%i==0 && n%i==0)
				gcd = i;
		System.out.printf("%d与%d的最大公约数是%d\n",m,n,gcd);
	}
}

2. Find the divisor between m / 2 ~ 1, and exit the loop when it is found

for(int i = m/2; i > 0; i--)
    if(m%i==0 && n%i==0)
    {
	  gcd = i;
      break;
    }

3. Euclidean algorithm (reverse phase division method)

public class Case25_GreatestCommonDivisor{
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("请输入两个正整数:");
		int m = in.nextInt();
		int n = in.nextInt();
		
		if(m>n)		//交换,确保m为较小者
		{
			m = m^n;
			n = m^n;
			m = m^n;
		}
		
		while(n%m != 0)
		{
			int temp = m;
			m = n%m;
			n = temp;
		}
		System.out.printf("%d与%d的最大公约数是%d\n",m,n,m);	
	}
}
Published 23 original articles · praised 7 · visits 1988

Guess you like

Origin blog.csdn.net/weixin_44641176/article/details/100107392