알고리즘 공부/CodeUp

1912 : (재귀함수) 팩토리얼 계산

콩이아부지이 2021. 10. 10. 15:41
728x90

팩토리얼(!)은 다음과 같이 정의된다.

n!=n×(n1)×(n2)××2×1n!=n×(n−1)×(n−2)×⋯×2×1

즉, 5!=5×4×3×2×1=1205!=5×4×3×2×1=120 이다.

nn이 입력되면 n!n!의 값을 출력하시오.

이 문제는 반복문 for, while 등을 이용하여 풀수 없습니다.

금지 키워드 : for while goto

입력

자연수 nn이 입력된다. (n<=12)(n<=12)

출력

n!n!의 값을 출력한다.

입력 예시   예시 복사

5

출력 예시

120

 

출처 : https://codeup.kr/problem.php?id=1912 

 

(재귀함수) 팩토리얼 계산

팩토리얼(!)은 다음과 같이 정의된다. $n!=n\times(n-1)\times(n-2)\times\cdots \times2\times1$ 즉, $5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$ 이다. $n$이 입력되면 $n!$의 값을 출력하시오. 이 문제는 반복문 for, while

codeup.kr

 

import java.util.Scanner;

public class Main {
		static int f(int n) {
			if(n == 1)return 1;
			return f(n-1)*n;
			}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		System.out.println(f(n));
	}//main end 
}
728x90