Bài 47: Đệ quy trong java

Ngày đăng: 1/2/2023 10:42:44 AM

Ví dụ về đệ quy trong java

Dưới đây là các ví dụ về cách sử dụng đệ quy trong java.

Ví dụ 1: vòng lặp vô tận

1

2

3

4

5

6

7

8

9

10    

public class RecursionExample1 {

    static void p() {

        System.out.println("hello");

        p();

    }

 

    public static void main(String[] args) {

        p();

    }

}

Kết quả:

 hello
 hello
 ...
 Exception in thread "main" java.lang.StackOverflowError
 

Ví dụ 2: vòng lặp có hạn

1

2

3

4

5

6

7

8

9

10     

11

12

13

14

15

public class RecursionExample2 {

    static int count = 0;

 

    static void p() {

        count++;

        if (count <= 5) {

            System.out.println("hello " + count);

            p();

        }

    }

 

    public static void main(String[] args) {

        p();

    }

}

Kết quả:

 hello 1
 hello 2
 hello 3
 hello 4
 hello 5
 

Ví dụ 3: tính giai thừa

1

2

3

4

5

6

7

8

9

10

11     

12

public class RecursionExample3 {

    static int factorial(int n) {

        if (n == 1)

            return 1;

        else

            return (n * factorial(n - 1));

    }

 

    public static void main(String[] args) {

        System.out.println("Giai thừa của 5 là: " + factorial(5));

    }

}

Kết quả:

 Giai thừa của 5 là: 120
 

Chương trình trên hoạt động như sau:

1

2

3

4

5

6

7

8

9

10     

factorial(5)

   factorial(4)

      factorial(3)

         factorial(2)

            factorial(1)

               return 1

            return 2*1 = 2

         return 3*2 = 6

      return 4*6 = 24

   return 5*24 = 120


Ví dụ 4: dẫy số Fibonacci

1

2

3

4

5

6

7

8

9

10

11

12    

13

14

15

16

17

18

19

public class RecursionExample4 {

    static int n1 = 0, n2 = 1, n3 = 0;

 

    static void printFibo(int count) {

        if (count > 0) {

            n3 = n1 + n2;

            n1 = n2;

            n2 = n3;

            System.out.print(" " + n3);

            printFibo(count - 1);

        }

    }

 

    public static void main(String[] args) {

        int count = 15;

        System.out.print(n1 + " " + n2); // in 0 và 1

        printFibo(count - 2);// n-2 vì 2 số 0 và 1 đã được in ra

    }

}

Kết quả:

 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Nguồn tin: viettuts