Coding Test

특정 숫자의 팩토리얼 구하기(Extra Long Factorials)

야뤼송 2017. 9. 8. 17:55
반응형

문제 출처:https://www.hackerrank.com

 

 문제 

어떤 자연수 N이 있을 때, N의 팩토리얼은 아래와 같다

 

N!= N x (N-1) x (N-2) x (N-3) x --- x 3 x 2 x 1

 

예를 들어 N이 25일 때 팩토리얼 값은 15511210043330985984000000 이다

 

참고로 N>20 인 경우 BigInteger를 사용해야만 가능하다

 

입력 받는 숫자의 팩토리얼을 구하라.

 

 

 풀이1

재귀함수를 통해 구현한다.

 

 소스코딩1

public class Solution { 	
    public static void main(String[] args) { 		
        Scanner in = new Scanner(System.in); 		
        int n = in.nextInt(); 		
        System.out.println( fact(n)); 	
    }      	

    public static BigInteger fact(int n){ 		
        BigInteger factVal = BigInteger.valueOf(n);          		
        
        if(n<=1){ 			
        	return factVal; 		
        }else{ 			
        	return factVal.multiply(fact(n-1)); 		
        } 	
    } 
}

 풀이2

재귀함수를 이용하지 않고 for문을 통해 구현한다.

 

 소스코딩2

public class Solution { 	
	public static void main(String[] args) { 		
		Scanner in = new Scanner(System.in); 		
		int n = in.nextInt();  		
		BigInteger factSum = new BigInteger("1"); 		
		BigInteger factVal = null;  		
		for(int i=0; i<n; i++){ 
			factVal=BigInteger.valueOf(n-i); 
			factSum=factSum.multiply(factVal); 
		} 
		System.out.println(factSum); 
	}
}
반응형