Using recursive method to find the factorial of n
The program invocation itself is called recursion (recursion). It usually transforms a large and complex problem layer into a small problem similar to the original problem.
The ability of recursion is to define an infinite set of objects with limited statements.
In general, recursion requires boundary conditions, recursive forward segments, and recursive return segments. When the boundary condition is not satisfied, recursion advances, and when the boundary condition is satisfied, recursion returns.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
long factorial (int n)
{
if (n = = 1) return
1;
else return
n*factorial (n-1);
}
int main (int argc,char *argv[])
{
int n = 0;
if (argc!= 2)
{
printf ("Input error,exit!! \ n ");
return-1;
}
n = atoi (argv[1]);
printf ("%d! =%ld\n ", n,factorial (n));
return 0;
}
Exercise examples
Topic
Topic Description:
Enter a positive integer n to output the factorial of N.
Input:
Positive integer N (0<=n<=1000)
Output:
Input may include multiple sets of data, for each set of input data, output n factorial
Sample input:
4
5
15
Sample output:
24
120
1307674368000
AC Code
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 3000//Save
Storing the result of each factorial operation int Str[max];
void calculatefactorial (int n);
int main () {int n;
while (scanf ("%d", &n)!= EOF) {if (n = = 0) {printf ("1\n");
else {calculatefactorial (n);
} return 0;
} void calculatefactorial (int n) {int i, J, temp, C, Len;
memset (str, 0, sizeof (str));
STR[1] = 1; for (i = 2, len = 1; I <= n; i + +) {//loops and 2,3,..
n multiplication for (j = 1, c = 0; J <= Len; j + +) {//str array represents a number, analog and I multiply temp = str[j] * i + C;
STR[J] = temp% 10;
c = TEMP/10;
while (C > 0) {str[j + +] = c% 10;
C/= 10;
len = j-1;
for (i = len; I >= 1; i-) {printf ("%d", str[i]);
printf ("\ n");
}
/**************************************************************
problem:1076
User:wangzhengyi
& nbsp; language:c
result:accepted
time:2150 Ms
memory:916 KB
****************************************************************/