[Javaアルゴリズム]7-3.実際の


🌼 Problem



🍔 Solution 1

import java.util.Scanner;

public class _73_팩토리얼 {

    static int answer =1;

    public static void Solution(int n){

        if(n==0) return;
        else{
            Solution(n-1);
            answer *= n;
        }
    }

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

        Solution(input);
        System.out.println(answer);
    }
}
[結果]

🍪 講師ソリューション

import java.util.Scanner;

public class _73_팩토리얼 {
	
    // 강사
    public static int Solution(int n){

        if(n==1) return 1;
        else return n*Solution(n-1);

    }

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

        System.out.println(Solution(input));
    }
}
Solution(5) = 5 × Solution(4) = 5 × (4×3×2×1) = 120
Solution(4) = 4 × Solution(3) = 4 × (3×2×1) = 24
Solution(3) = 3 × Solution(2) = 3 × (2×1) = 6
Solution(2) = 2 × Solution(1) = 2 × 1 = 2
Solution(5) = 120