There are two simple examples of Java recursive algorithm

  • 2020-11-03 22:07:12
  • OfStack

This article gives an example of the Java recursive algorithm. To share for your reference, the details are as follows:

1. To achieve the sum of 1 to 100, with recursive implementation


public class RecursionTest {
  public static void main(String[] args) {
    System.out.println(diGui(100));// 5050
  }
  public static int diGui(int n) {
    int sum;
    if (n == 1)
      return 1;
    else {
      sum = n + diGui(n - 1);
      return sum;
    }
  }
}

2. Recursively multiply by 1 to 100


public class RecursionTest {
  public static void main(String[] args) {
    System.out.println(diGui(5));// 120  Notice that if I take 100 The factorial of phi then doesn't work int or long, The calculated result is too large for the program to return, 1 The general case returns 0 Want to use BigInteger
  }
  public static int diGui(int n) {
    int sum;
    if (n == 1)
      return 1;
    else {
      sum = n * diGui(n - 1);
      return sum;
    }
  }
}

For more information about java algorithm, please refer to Java Data Structure and Algorithm Tutorial, Java DOM Node Operation Skills Summary, Java File and Directory Operation Skills Summary and Java Cache Operation Skills Summary.

I hope this article has been helpful in java programming.


Related articles: