비트교육_단기과정
팩토리얼을 재귀함수로 구현
ELpsy
2022. 7. 13. 14:12
package week_4; // 팩토리얼 값을 재귀적으로 구함 import java.util.Scanner; class Factorial { // for문으로 팩토리얼 값을 반환 static int factorialFor(int n) { for (int i = n - 1; i > 0; i--) { n = n * i; } return n; } // --- 음이 아닌 정수 n의 팩토리얼 값을 반환 ---// static int factorial(int n) { return (n > 1) ? n * factorial(n - 1) : 1; } public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); System.out.print("정수를 입력하세요 : "); int x = stdIn.nextInt(); System.out.println(x + "의 팩토리얼은 " + factorial(x) + "입니다."); System.out.println(x + "의 팩토리얼은 " + factorialFor(x) + "입니다."); } } | cs |