study/코드리뷰

0313 코드리뷰 Q2. 팩토리얼 메소드

달거북씨 2022. 3. 15. 14:13

Q2. 파라미터로 양의 정수 n을 받고 n!을 계산해서 리턴해주는 메소드를 만들어 보세요!
*주의* 0!은 1입니다. System.out.println(factorial(0)); -> 1 출력

 

팩토리얼이란?
기호는 n!로 나타내며 1부터 어떤 양의 정수 n까지의 정수를 모두 곱한것을 말한다.
팩토리얼 예시) 2! -> 1 * 2 = 2 , 5! -> 1 * 2 * 3 * 4 * 5 = 120

예) System.out.println(factorial(6));
출력결과 -> 720

 

 

 

A2. factorial 문제는 모두 비슷하게 풀었다

public class MKY_Factorial {

	public static void main(String[] args) {
		int result = factorial(6);
		System.out.println("팩토리얼 출력결과 : " + result);
	}

	public static int factorial(int n) {
		int mul = 1;	// n! = n부터 1까지 숫자를 곱하는 것이므로 변수를 1로 초기화
		if(n==0) {	// factorial 0의 값은 1이므로 따로 설정해준다.
			return 1;
		} else {	// 0외에 다른 숫자는 else문에 들어온다.
			for (int i = 0; i < n; i++) {
				mul = mul * (n-i);
			}
			return mul;
		}
	}
}

 

728x90