Java recursive deep understanding of _java

Source: Internet
Author: User

One, recursive function, popular say is the function itself call itself ...

such as: N!=n (n-1)!
You define the function f (n) =nf (n-1)

and f (n-1) is the function of this definition. This is recursion.

Second, why to use recursion: The purpose of recursion is to simplify program design, make the program easy to read

The drawback of recursion: although the non recursive function is high efficiency, but it is difficult to program, the readability is poor. The disadvantage of a recursive function is that it increases the overhead of the system, which means that the stack memory takes up a bit more than once per recursive

Four, the recursive condition: must have completes the task the statement, needs to satisfy the recursive request (reduces rather than the divergence)

Five, recursive advanced:
1. Use recursion to calculate the factorial of N:

Analysis: n!=n* (n-1) * (n-2) ... *1

 public int Dreturn (int n) { 
   if (n==1) {return 
    1; 
   } else{return 
    N*dreturn (n-1); 
   } 
  

2. The summation of 1 to n is calculated by recursive function: 1+2+3+4+. +n

 public int Dreturn (int n) { 
  if (n==1) {return 
   1; 
  } else{return 
   N+dreturn (n-1); 
  } 
 

3. Request output a sequence: 1,1,2,3,5,8,11 ... (each number is the sum of the first two digits, the recursive function is required)
Using Java recursion to represent a function: F (n) =f (n-1) +f (n-2); F (0) = 1; F (1) = 1;
Analysis: x1=1; X2=1; x3=x1+x2; x4=x2+x3; ... ; Xn=x (n-1) +x (n-2)

  public int F (int n) { 
  if (n==1) {return 
   1; 
  } else if (n==2) {return 
   1; 
  } else{return 
    F (n-1) +f (n-2); 
  } 
 

4.java reverse printing of each element in an array of integers by recursive method

  public static void printall (int index,int[] arr) { 
   System.out.println (Arr[index]); 
   if (Index > 0) { 
    printall (--index,arr); 
   } 
  } 
  public static void Main (string[] args) { 
   int[] arr={1,2,3,4,5}; 
   Printall (Arr.lenth-1,arr); 
  

5. Programmatic solution: If a heifer, from the fourth year of birth, start a yearly cow, according to the law, how many cows in the nth years?

  public static int cattle (int n) { 
if (n<=0) {return 
 0; 
} else if (n<=3) {return 
 1; 
} else{return 
 cattle (n-1) +cattle (n-3); 
} 
  public static void Main (string[] args) { 
   int n=10; 
   System.out.println (n+ "Years after" +cattle (n) + "cow"); 
  

The concept of recursion, linear recursion, and tail recursion?

Invocation of recursive functions in Java--to find the factorial of a number

Do not consider overflow: generally can only count to 69 factorial ...

Note: 0 factorial 0! =1


Any natural number that is greater than 1 the n factorial representation method:
N!=1x2x3x......xn
or N!=NX (n-1)!
Search 0 factorial, can come out an online calculator, very practical Oh!!

Package test;

Import Java.util.Scanner;

public class Digui {public
	static void Main (string[] args) {
		//TODO auto-generated method stub
		SYSTEM.OUT.PR Intln ("Enter an integer:");
		Scanner scan = new Scanner (system.in);
		int x = Scan.nextint ();
		int result = Digui (x);
		SYSTEM.OUT.PRINTLN (result);
	}
	
	Recursive function public
	static int Digui (int x) {
		if (x<=0) {return
			1;
		} else{return
			X*digui (x-1);
		}
	}

Recursion: a process or function that, in its definition or description, has a method of calling itself directly or indirectly, which usually transforms a large and complex problem layer into a small problem similar to the original problem. This case is a clear illustration of how recursion solves a complex problem by translating it into smaller problems. The following is a small example to illustrate the principle of recursion.

/**
* @fileName Test.java
* @description??????????
* @date 2012-11-25
* @time 17:30
* @author WST
/public class Test {
  static int multiply (int n) {
   
    int factorial; // ?? 

    if ((n = = 1) | | (n = = 0)) {
      factorial = n;
    } else {
      factorial = n * Multiply (n-1);
    }

    return factorial;
  }

  public static void Main (string[] args) {
    System.out.println (multiply (5));
  }


   

When a function is called, the space of its variables is created on the Run-time stack. The variables of previously called functions are left on the stack, but they are obscured by the variables of the new function and therefore cannot be accessed.
The function in the program has two variables: parameter n and local variable factorial. Some of the following graphs show the state of the stack, and the currently accessible variable is at the top of the stack. All other variables that are called are decorated with shades of gray, indicating that they cannot be accessed by the function currently executing.
Suppose we call a recursive function with a value of 5. The contents of the stack are as follows, with the top of the stack at the bottom:

n Multiply (n) factorial 
5 Multiply (5) 5*multiply (4)//First Call 4 multiply (4) 
4*multiply (3)//second call 
3 Multiply (3) 3*multiply (2)//Third call 
2 multiply (2) 2*multiply (1)//fourth time call 

From the above information can easily see how recursion is to minimize a problem to solve, starting from the method call, the factorial results will be pushed into the stack until the method call ends, and finally from the top of the stack back to get the results. The results are as follows:
N=1 1 up 1
n=2 2*multiply (1) up back 2*1=2
n=3 3*multiply (2) up 3* (2*1) =6
n=4 4*multiply (3) go up 4* (3* (2*1)) =24
n=5 5*multiply (4) go up 5* (4* (3*)) 2*1
Note: Because =120 (1) or multiply (0) returns a value of 1
so there is 2*multiply (1) =2*1=2
also because multiply (2) conforms to recursive conditions and can be converted to 2*multiply (1)
So there is 3*multiply (2) =3* (2*multiply (1)) =3* (2*1) =6
Because multiply (3) can be recursively converted to 3*multiply (2)
so multiply (4) =4*multiply (3) =4* (3*multiply (2)) =4* (3* (2*1)) =24
and so on , multiply (5) =5*multiply (4)
can be converted to 5* (4*multiply (3)) =5* (4*3* (Multiply (2)) =5* (4* (3* (2*1))) =120
To see bytecode information again:

public class Test extends java.lang.object{public test (); code:0: Aload_0 1:invokespecial #1; Method Java/lang/object. " 
<init> ":() V 4:return static int multiply (int); code:0: Iload_0 1:iconst_1//Push the int type constant 1 into the stack 2:if_icmpeq 9//Compare two int type values, equal, then jump to position 9, this is | | Short circuit function 5:iload_0//Here is the first condition is not established in the case of the implementation, load the int type value from local variable 0 (push the value of n into the stack) 6:ifne 14//comparison, and if not equal to 0, jump to position 14, note: Because of the default and 0 comparisons here, So there is no need to press the constant 0 into the stack 9:iload_0//If there is no jump at the Ifne place, then load the int type value from local variable 0 (push the value of n into the stack) 10:istore_1///The Int type value is stored in local variable 1 (the value that pops up the top of the stack is the value of the local variable 0 that is pushed into the stack, Save in local variable 1) 11:goto 23//unconditionally jump to position 14:iload_0//Position 6 comparison, if not equal to 0 execute this instruction, load int type value from local variable 0 (push the value of n into stack) 15:ILOAD_0//Load i from local variable 0 NT Type value (pushes n's value into stack) 16:iconst_1//pushes the int type constant 1 into the stack, and the constant 1 is the n-1 1 17:isub//performing subtraction operation in the code, n-1 18:invokestatic #2; 
Method Multiply: (i) I, calling methods multiply 21:imul//performing multiplication operations, n * Multiply (n-1) 22:istore_1//storing int type values in local variable 1, factorial= ... 
23:iload_1//loads the int type value from local variable 1 (pushes the factorial result into the stack) 24:ireturn//method returns public static void Main (java.lang.string[)); code:0: Getstatic #3; Field Java/lang/system.out:ljava/io/printstream; 3:iconst_5 4:invokestatic #2; Method Multiply: (i) I 7:invokevirtual #4;  Method Java/io/printstream.println: (I) V 10:return}

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.