Use the C language to find N factorial method

  • 2020-04-02 03:14:10
  • OfStack

So we recursively take N factorial

Program calls themselves are called recursion. They usually solve a large, complex problem by converting it layer by layer into a smaller problem similar to the original one.

The power of recursion is to define infinite collections of objects in finite statements.

In general, recursion requires boundary conditions, recursive forward segments, and recursive return segments. When the boundary condition is not satisfied, recursively advance; When the boundary condition is satisfied, the 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! = %ldn",n,factorial(n));

  return 0;

}

Problem sets sample

The title

      Title description:  
        Input a positive integer N, output N factorial.  
      Input:  
      Positive integer N (0 < = N < = 1000).  
      Output:  
        The input may contain multiple sets of data, and for each set of input data, the 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 
    
  //Store 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("1n"); 
      } 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 ++) { //Circulation and 2, 3,.. N multiplication
      for (j = 1, c = 0; j <= len; j ++) { //The STR array represents a number multiplied by I
        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
              Language: C
              Result: Accepted
              Time: 2150 ms
              Memory: 916 KB
      * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /


Related articles: