[자바 알고리즘] 39. 최대공약수

김건우's avatar
Feb 12, 2025
[자바 알고리즘] 39. 최대공약수
package algo; public class Util { // 두 정수 A와 B를 인자로 받아 최대 공약수를 재귀적으로 계산합니다. // B가 0일 경우 A가 최대 공약수입니다. // 그 외의 경우에는 GCD(B, A % B)를 호출하여 최대 공약수를 계속 계산합니다. static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } }
💡
유클리드 호제법
(a, b) = (b, a % b)
4와 24의 최대 공약수를 구하시오!
4의 약수: 1, 2, 4 24의 약수: 1, 2, 3, 4, 6, 8, 12, 24 공통 약수: 1, 2, 4
while (true){ System.out.println("1라운드"); c = a%b; a=b; b=c; if(c==0){ break; } System.out.println("최대공약수 : " + a)
import java.util.Scanner; public class GCD01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("두 정수를 입력하세요 (A B): "); int a = scanner.nextInt(); int b = scanner.nextInt(); int result = Util.gcd(a, b); System.out.println("두 수 " + a + "와 " + b + "의 최대 공약수는: " + result); } }
notion image
Share article

gunwoo