[파이썬][백준 10872번] 팩토리얼
1. 문제Permalink
[Bronze III] 팩토리얼 - 10872Permalink
성능 요약Permalink
메모리: 30864 KB, 시간: 68 ms
분류Permalink
구현(implementation), 수학(math)
문제 설명Permalink
0보다 크거나 같은 정수 N이 주어진다. 이때, N!을 출력하는 프로그램을 작성하시오.
입력Permalink
첫째 줄에 정수 N(0 ≤ N ≤ 12)이 주어진다.
출력Permalink
첫째 줄에 N!을 출력한다.
출처: 백준, https://https://www.acmicpc.net/
2. 해결방법 시간복잡도Permalink
- 단순 코딩, 재귀문 1번 호출 O(N)
3. 문제 해결 및 코드Permalink
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def factory(N): # 팩토리 정의 | |
result = 1 # 기본값 1로 정의 | |
if N > 0: # 넣는 값이 0 이상일 경우 | |
result = N * factory(N-1) # 결과값은 입력값 * 이전 주소값 | |
return result # 결과값 리턴 | |
N = int(input()) | |
print(factory(N)) |
-
주석을 참고하면서 이해를 돕습니다.Permalink
4. 알고리즘 및 해설Permalink
- N!를 구하기위해 재귀문을 통해 해당 값 - 1을 반복적으로 호출하여 최종적으로 해당 정수까지의 곱을 구한다.
- F(N) = F(N - 1) * F(N - 2) * … F(0)
5. 짚고 넘어가기Permalink
- 팩토리얼 문제는 1부터 해당 수까지의 곱이다. 단순 반복으로도 해결이 가능하다.
- math 라이브러리를 통해서 간단하게 구현도 가능하다.
import math
print(math.factorial(N)) # N값까지의 팩토리얼