CS/손코딩

팩토리얼

졔졔311 2023. 6. 21. 15:39
728x90
반응형

팩토리얼은 1부터 자기자신까지의 값을 모두 곱한 값이다.

식으로 표현하면 다음과 같다.

n! = 1 x 2 x ... x (n-1) x n


1. 재귀를 이용한 구현

#include <iostream>

using namespace std;

int fact(int n){
    if(n <= 1){
        return n;
    }
    return n * fact(n-1);
}

// 재귀를 이용한 팩토리얼
int main(void){
    int n;
    cin >> n;

    cout << fact(n) << "\n";

    return 0;
}

 

2. 반복문을 이용한 구현

#include <iostream>

using namespace std;

// 반복문을 이용한 팩토리얼
int main(void){
    int n;
    cin >> n;

    int ans = 1;
    for(int i = 1; i <= n; i++){
        ans *= i;
    }
    cout << ans << "\n";

    return 0;
}

 

728x90
반응형

'CS > 손코딩' 카테고리의 다른 글

[정렬] Merge Sort  (0) 2023.06.21
[정렬] Insertion Sort  (0) 2023.06.21
[정렬] Selection Sort  (0) 2023.06.21
[정렬] Bubble Sort  (0) 2023.06.21
피보나치 수열  (0) 2023.06.21