C

[C]백준 10.재귀: 10872

열지희공 2022. 1. 16. 21:17

백준 10872

내코드

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int factorial(int n) {
	if (n == 0) {
		return 1;
	}
	else {
		return n * factorial(n - 1);

	}
}

int main()
{
	int n;
	scanf("%d", &n);
	printf("%d",factorial(n));
	return 0;
}

factorial은 1부터 n까지 모두 곱하면 되기에 n이 0일땐 1을 리턴하고, 그외엔 n*factorial(n-1)을 리턴하는 함수를 만들었다. 

예를 들어 factorial(4)를 호출한다면 4*factorial(3)이 리턴되기 전 factorial(3)이 호출될 것이다. factorial(3)은 3*factorial(2)를 리턴하기 전 factorial(2)를 호출할 것이다. factorial(2)는 2*factorial(1)을 리턴하기 전 factorial(1)을 호출할 것이다. factorial(1)은 1*factorial(0)을 리턴하기 전 factorail(0)을 호출할 것이다. factorial(0)이 1을 리턴하면 factorial(1)은 1*1=1을 리턴할 것이고, factorial(2)는 2*1=2를 리턴할 것이다. factorial(3)은 3*2=6을 리턴할 것이고, factorial(4)는 4*6=24를 리턴하게 될 것이다.