学习笔记1 | GCD(Greatest Common Divisor)最大公约数的算法

匿名 (未验证) 提交于 2019-12-02 23:00:14

参考https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm

largest integer that divides both A and B.

Euclidean AlgorithmGCD

The Algorithm

The Euclidean Algorithm for finding GCD(A,B) is as follows:

  • Find GCD(B,R) using the Euclidean Algorithm since GCD(A,B) = GCD(B,R)

Example:

Find the GCD of 270 and 192

  • A=270, B=192
  • A ≠0
  • B ≠0
  • Use long division to find that 270/192 = 1 with a remainder of 78. We can write this as: 270 = 192 * 1 +78
  • Find GCD(192,78), since GCD(270,192)=GCD(192,78)

A=192, B=78

  • A ≠0
  • B ≠0
  • Use long division to find that 192/78 = 2 with a remainder of 36. We can write this as:
  • 192 = 78 * 2 + 36
  • Find GCD(78,36), since GCD(192,78)=GCD(78,36)

A=78, B=36

  • A ≠0
  • B ≠0
  • Use long division to find that 78/36 = 2 with a remainder of 6. We can write this as:
  • 78 = 36 * 2 + 6
  • Find GCD(36,6), since GCD(78,36)=GCD(36,6)

A=36, B=6

  • A ≠0
  • B ≠0
  • Use long division to find that 36/6 = 6 with a remainder of 0. We can write this as:
  • 36 = 6 * 6 + 0
  • Find GCD(6,0), since GCD(36,6)=GCD(6,0)

A=6, B=0

  • A ≠0
  • B =0, GCD(6,0)=6

So we have shown:

GCD(270,192) = GCD(192,78) = GCD(78,36) = GCD(36,6) = GCD(6,0) = 6

GCD(270,192) = 6

通过递归的方法实现并检验:

 class GCD{ 	public int GCD(int a, int b){ 		if(b == 0){ 			return a; 		} 		else{ 			return GCD(b, a%b); 		} 	}  	public static void main(String[] args) { 		GCD ob = new GCD(); 		int result = ob.GCD(270, 192); 		System.out.print(result); 	} }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!