ruby-recursion and tail recursion

Source: Internet
Author: User

The difference between recursion and iteration

Recursion:

1) recursion is the invocation of itself within a procedure or function;

2) When using recursion, there must be a definite recursive end condition called a recursive exit.

Iteration:

Use the original value of the variable to derive a new value for the variable. If recursion calls itself, the iteration is a non-stop call to B.

1, Fibonacci 1 1 2 3 5 8

Recursive algorithm

def fibo1 (N)
If N==1 or n==2
return 1;
End
Fibo1 (n-1) +fibo1 (n-2)
End
Puts Fibo1 (6);

Tail recursion, which takes each result into the next operation, much like the iteration.

def Fibo2 (N,g,k)
Puts K
A=k
K=g+k
G=a
If N==1
Return K
End
Fibo2 (N-1,g,k)
End

Puts Fibo2 (5,0,1)

Iteration

def FIBO3 (N)
j,k=0,1
Puts J
Puts K

For I in 1..N
A=k
K=j+k
J=a
Puts K
End
End

2. Factorial

Tail recursion

def fact (N,g)
If n==0
return g;
End
Fact (N-1,N*G)
End

ruby-recursion and tail recursion

Related Article

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.