알고리즘 공부/정올 문제풀이

[정올] 1309 : 팩토리얼 -(JAVA)

송테이토 2022. 9. 2. 17:32

1309 : 팩토리얼

문제

1부터 어떤 양의 정수 n까지의 정수를 모두 곱한 것을 말하며 n!로 나타낸다.


0! = 1

1! = 1

2! = 2

n! = n * (n-1)!

와 같이 정의된다.

 

예로 4! = 4×3×2×1 = 24 이다.

 

n! 이 주어졌을 때 결과를 출력하는 프로그램을 작성하라.

 

* 결과가 int범위를 넘는 경우 

자료형 long long 

입력/출력 서식문자 %lld 

를 사용한다.

 

입력형식

입력은 한 줄로 이뤄지며 팩토리얼의 숫자 n(1≤n≤15)이 입력된다.

 

 

출력형식

n!에 대한 계산 결과를 "출력예"처럼 과정을 출력하고 마지막에 결과를 출력한다.

 


 

풀이

import java.util.Scanner;

public class J1309 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		sc.close();

		long sum = 1; //long으로 선언!
		for (int i = n; i > 0; i--) {

			sum *= i; // n! 의 총 합

			if (i - 1 == 0) {
				System.out.println(i + "! = " + i);
			} else {
				System.out.println(i + "! = " + i + " * " + (i - 1) + "!");
			}
		}
		System.out.println(sum);
	}

}

 


재귀함수로도 풀 수 있다.

import java.util.Scanner;

public class Main {
   public static long factorial(long p) {
      if (p == 0)
         return 1;
      else {
         System.out.print(p + "! = ");
         if (p == 1)
            System.out.println(p);
         else
            System.out.println(p + " * " + (p - 1) + "!");
         return p * factorial(p - 1);
      }
   }

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      long n = sc.nextInt();
      sc.close();

      System.out.println(factorial(n));
   }
}