Ways to eliminate recursion

Source: Internet
Author: User

1, if the recursion is the tail recursion, the use of the loop can be eliminated, tail recursion is the function at the end of the recursive call this function, the following format is satisfied:

int  function (int n) {if (n==0) return 1;else return function (n-1);}

The tail recursion uses the loop, uses the result of the N=1, defines a variable to remember the res, then loops slowly calculates the n=2, 3 .... The result is that each time the value of n is calculated, the res will remember that each time the value of the function is computed using res, the following gives an example of calculation

#include <stdio.h>
Recursive method int fib (int n) {if (n==1) return 1;if (n==0) return 0;else return fib (n-1) +fib (n-2);}
Non-recursive method int fib2 (int n) {if (n==1) return 1;else if (n==0) return 0;int fib0=0;int fib1=1;int result=0;for (int x=2;x<=10;x+ +) {Result=fib0+fib1;fib0=fib1;fib1=result;} return result;} void Main () {int A=fib (ten), int b=fib2 (TEN);p rintf ("A's value is:%d\n", a);p rintf ("B's value is:%d\n", b);}

2, if the non-recursive need to be based on the stack to eliminate recursion, the detailed process is visible: Shang, data structure 129 pages.

Ways to eliminate recursion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.