Is recursive functions in C language really good?
Recursive functions call their own functions directly or indirectly. We often see this program when dealing with recursion.
#include<stdio.h>#include<stdlib.h>long factorial(int n){ if (n <= 0) return 1; else return n*factorial(n - 1);}int main(){ int n = 5; printf("%ld\n", factorial(n)); system("pause"); return 0;}
This is a recursive function used to calculate factorial !! But is it really good? The answer is no! The execution efficiency of this program is very low, because the overhead of each function call is very large, and factorial () is continuously called () functions need to open up space on the stack (most compilers perform recursion on the stack). It is really bad to write such functions! The following program also completes the above results:
#include<stdio.h>#include<stdlib.h>long factorial(int n){ int result = 1; while (n > 1) { result *= n; n--; } return result;}int main(){ int n = 5; printf("%ld\n", factorial(n)); system("pause"); return 0;}
The 5 factorial is completed, but the efficiency is much higher. Here we only use one loop. When talking about the Fibonacci series, you must still think of Recursive Implementation:
#include<stdio.h>#include<stdlib.h>long fibonacci(int n){ if (n <= 2) return 1; return fibonacci(n - 1) + fibonacci(n - 2);}int main(){ int n = 5; printf("%ld\n", fibonacci(n)); system("pause"); return 0;}
Find the fifth number in the Fibonacci series. The previous value is used each time you evaluate the number. Two recursive calls are initiated for each call, which is costly. However, it is very convenient to implement it using iterative methods:
# Include <stdio. h> # include <stdlib. h> // calculate maid (int n) {long result = 0; long first = 0; long second = 0; result = first = 1; while (n> 2) // The efficiency is much higher than recursion {n-= 1; second = first; first = result; result = first + second;} return result;} int main () {int n = 5; printf ("% ld \ n", maid (n); system ("pause"); return 0;} this overlap
The generation process is as follows: because the last digit of the fibonacci series is the first two and second first result 1 1 1 2 2 2 3 2 3 5 3 5 8 ...... this efficiency is much higher than recursion. It seems that Recursive Implementation is not all good, so if you think of recursion when you encounter a problem, first, you should think about whether the benefits of recursion can offset the cost paid by it!