Java

팩토리얼

충 민 2022. 7. 14. 19:52

!=팩토리얼 

n은 입력한 수

1부터 n까지 모든 자연수를 곱한다

import java.util.Scanner;
public class Factorial {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in) ;
		int num;
		while(true) {
			System.out.println("수를 입력하세요");
			num = sc.nextInt();
			if(num>0) {
				System.out.println(fact(num)+"\t");
				System.out.println(factWhile(num));
				
			}
			else break;
		}
	}

public static int fact(int n) {
	if(n>0) {
		return n*fact(n-1);
	}
	else return 1;
	
}
public static int factWhile(int n) {
	int result = 1;
	while(n>0) {
		result *=n;
		n--;
	}
	return result;
}
}