상세 컨텐츠

본문 제목

[C++] int보다 큰 정수 타입과 팩토리얼(!)

카테고리 없음

by 별달하현 2023. 7. 13. 19:56

본문

int type 변수의 표현 범위는 10자리수 까지이다.

그것을 넘어가는 자릿수를 표현하기 위해서는 int64_t라는 type 선언이 필요하다.

이것에 필요한 라이브러리는 cstdint이다.

팩토리얼(!)의 경우, 금방금방 숫자의 자릿수가 커지기에, int type이 아닌, int64_t 로 설정해야한다.

 

#include <iostream>
#include <cstdint>
using namespace std;

int64_t factorial(int cnt) {

    if (cnt <= 1) {
        return 1; // 0! = 0 , 1! = 1
    }
    return factorial(cnt - 1) * cnt;
}

int main() {
    int64_t num;
    cin >> num;

    cout << factorial(num);
    
    return 0;
}