logo

Python의 계승()

아는 사람은 많지 않지만 Python은 계승 계산을 위한 전체 코드를 작성하지 않고도 숫자의 계승을 계산할 수 있는 직접 함수를 제공합니다.

계승을 계산하는 순진한 방법



파이썬3






삽입 정렬

# Python code to demonstrate naive method> # to compute factorial> n>=> 23> fact>=> 1> for> i>in> range>(>1>, n>+>1>):> >fact>=> fact>*> i> print>(>'The factorial of 23 is : '>, end>=>'')> print>(fact)>



>

>

산출

The factorial of 23 is : 25852016738884976640000>

시간 복잡도: 에)
보조 공간: 오(1)

math.factorial() 사용

이 방법은 다음에 정의되어 있습니다. 수학 파이썬 모듈. C타입으로 내부 구현되어 있어서 속도가 빠릅니다.

 math.factorial(x) Parameters : x : The number whose factorial has to be computed. Return value : Returns the factorial of desired number. Exceptions :  Raises Value error if number is negative or non-integral.>

파이썬3




# Python code to demonstrate math.factorial()> import> math> print>(>'The factorial of 23 is : '>, end>=>'')> print>(math.factorial(>23>))>

>

>

산출

The factorial of 23 is : 25852016738884976640000>

시간 복잡도: 에)
보조 공간: 오(1)

math.factorial()의 예외

    주어진 숫자가 음수인 경우:

파이썬3

bash에서 if와 else




# math.factorial()을 보여주는 Python 코드
# 예외(비정수)

수학 가져오기

print(5.6의 계승은 : , end=)

# 예외 발생
인쇄(math.factorial(5.6))

>

>

산출:

Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values>
    주어진 숫자가 Non – 적분값인 경우:

파이썬3




>

>

산출:

Traceback (most recent call last): File '/home/3987966b8ca9cbde2904ad47dfdec124.py', line 9, in print (math.factorial(5.6)) ValueError: factorial() only accepts integral values>