just do it

유클리드호제법, 재귀함수, 최대공약수 출력하기(java) 본문

자료구조&알고리즘/코딩테스트

유클리드호제법, 재귀함수, 최대공약수 출력하기(java)

밍풀 2022. 10. 27. 03:30

유클리드호제법, 재귀함수 이용 최대공약수 출력하기 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
 
public class recursion {
 
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        System.out.print("Please enter an x : ");
        int x = sc.nextInt();
        System.out.println("Please enter an y : ");
        int y = sc.nextInt();
        int answer= gcd(x,y);
        System.out.print("the answer is : "+ answer);
        
 
    }
    //유클리드호제법 & 재귀 
    static int gcd(int x, int y) {
        if(y==0) {
            return x;
        }
        else return gcd(y, x%y);
    }
 
}
 
cs