본문 바로가기

Java

재귀 알고리즘

재귀 알고리즘

  • 어떤 사건이 자기 자신을 포함하고 다시 자기 자신을 사용하여 정의될 때 재귀적이라고 한다.
public class Factorial {

    public static int factorial(int n) {

        if (n > 0) {
            return n * factorial(n - 1);
        } else {
            return 1;
        }

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("정수를 입력하세요 : ");
        int n = scanner.nextInt();

        System.out.printf("%d의 팩토리얼은 %d입니다.", n, factorial(n));

    }

}

 

public class EuclidGCD {

    public static int gcd(int x, int y) {

        if (y == 0) {
            return x;
        } else {
            return gcd(y, x % y);
        }

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("두 정수의 최대공약수를 구합니다.");

        System.out.print("정수를 입력하세요 : ");
        int x = scanner.nextInt();

        System.out.print("정수를 입력하세요 : ");
        int y = scanner.nextInt();

        System.out.println("최대공약수는 " + gcd(x, y) + "입니다.");

    }

}
728x90

'Java' 카테고리의 다른 글

[Spring] @RequestBody vs @RequestParam  (0) 2024.07.10
[Spring] @Controller VS @RestController  (0) 2024.07.09
Interface  (0) 2024.07.02
추상 클래스 (Abstract Class)  (0) 2024.07.01
Serialization (직렬화)  (0) 2024.06.28