当前位置:网站首页>如何求最大公约数?

如何求最大公约数?

2022-08-09 12:25:00 进击的李知因

1、在1~m/2之间找约数,最后的约数即最大公约数

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、在m/2~1之间找约数,找到就退出循环

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

3、欧几里德算法(辗转相除法)

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);	
	}
}
原网站

版权声明
本文为[进击的李知因]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44641176/article/details/100107392