Recursion Function

Factorial ๊ฐ™์€ ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š”, ์ž๊ธฐ์ž์‹ ์˜ ์ถœ๋ ฅ๊ฐ’์„ ๋‹ค์‹œ ๋ถˆ๋Ÿฌ์•ผ ๋˜๋Š” ํ•„์š”์„ฑ์ด ์žˆ๋‹ค. ์ด๊ฒƒ์„ย ์žฌ๊ท€ํ•จ์ˆ˜๋ผ ํ•œ๋‹ค.

Example

#include <iostream>
using namespace std;
 
int factorial(int n);
 
int main(){
    cout << factorial(0) << endl;
    cout << factorial(1) << endl;
    cout << factorial(6) << endl;
    cout << factorial(10) << endl;
    
    return 0;
}
 
int factorial(int n){
    if (n == 0)							// ์ œ์•ฝ์กฐ๊ฑด
        return 1;
    else
        return n * factorial(n-1);
}

์ด ๊ณผ์ •์„ ์•Œ์•„๋ณด๋ฉด,

6์ผ ๋•Œ,ย n-1 factorialย ์„ ๋ถˆ๋Ÿฌ์•ผ ํ•˜๋ฏ€๋กœ 5 factorialย ๋กœ ๊ฐ„๋‹ค. ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ์ œ์•ฝ์กฐ๊ฑด์ธย n==1ย ์ผ ๋•Œ๊นŒ์ง€ ๊ฐ”๋‹ค๊ฐ€, ๋„์ฐฉํ•˜๋ฉด ์ˆœ์ฐจ์ ์œผ๋กœ ๊ฐ’์„ ์–ป์–ด์™€ ์ตœ์ข… ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Reference