팩토리얼 알고리즘

음수면 예외처리 발생시키기 (문자 출력)
n>0일 때 재귀
0 == 0일 때 (0!은) 1
import java.util.*;
import java.lang.*;

// n! = n*(n-1)
public class factorial {
    static int factorial(int n) throws Exception{
        // n>0, n!
        /*계속 팩토리얼 발생*/
        if (n > 0)
            return (n * factorial(n-1));
        // n == 0
        /*0! = 1*/
        else if (n == 0)
            return 1;
        // n < 0
        /*예외 발생시키기*/
        else
            throw new Exception("n+의 팩토리얼은 구할 수 없습니다.");
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        //n 입력 받기
        System.out.println("팩토리얼 값: ");
        int n = sc.nextInt();

        factorial(n);
        System.out.println(n+"의 팩토리얼: "+factorial(n));
    }
}

유클리드 호제법_최대공약수(GCD)

import java.util.*;

//최대공약수 구하기
//gcd = x%y
public class GCD {

    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 sc = new Scanner(System.in);

        System.out.println("첫 번째 정수값: ");
        int x = sc.nextInt();
        System.out.println("두 번째 정수값: ");
        int y = sc.nextInt();

        System.out.println("두 정수값의 최대 공약수: "+gcd(x,y));
    }
}

하노이의 탑(Hanoii)

그룹 묶어서 중간기둥으로 옮기기
no: 사이즈, x: 시작기둥번호, y: 목표기둥번호
import java.util.*;

public class hanoii {
    static int hanoii(int no, int x, int y){
        if(no > 1)
            hanoii(no-1, x, 6-x-y);
        System.out.println("원반" + no + "을" + x + "기둥에서" + y + "기둥으로 옮긴다.");

        if(no > 1)
            hanoii(no - 1, 6-x-y, y);
        return 0;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("원반 개수: ");
        int n = sc.nextInt();
        hanoii(n,1,3);
    }
}
profile
정리.velog

0개의 댓글