Java中的遞歸定義為「一個方法直接或間接地連續呼叫自身(同一個方法)」。遞歸函數用於需要一次又一次執行同一組操作直到得出結果的情況。它執行多次迭代,並且每次迭代問題陳述都變得越來越簡單。 java中的遞歸是一種基於相同問題的較小區塊的解來解決問題的方法。大多數無限可能的迭代都可以透過遞歸來解決。我們可以說遞歸是循環語句的另一種方法。如果我們沒有正確使用遞歸函數,那麼它會執行無限次。
文法:
廣告 該類別中的熱門課程 JAVA 掌握 - 專業化 | 78 課程系列 | 15 次模擬測驗returntype methodName() { //logic for application methodName();//recursive call }
要停止無限條件,我們必須滿足以下條件:
我們可以用兩種方式呼叫遞歸函數:
如果我們從內部方法體呼叫相同的方法。
文法:
returntype methodName() { //logic for application methodName();//recursive call }
範例:
數字的階乘是直接遞歸的一個例子。遞歸的基本原理是透過將複雜問題分解為更小的問題來解決它。例如,對於一個數字的階乘,如果我們知道「i-1」的階乘,我們就可以計算出「i」的階乘。
代碼:
public class Factorial { static int fact(int i){ if (i == 1) return 1; else return(i * fact(i-1)); } public static void main(String[] args) { System.out.println("The factorial of given number 6 is: "+fact(6)); } }
輸出:
如果我們從另一個方法呼叫一個方法,並且從第一個方法呼叫另一個方法,反之亦然。
文法:
<firstIndirectRecursive() { // Logic secondIndirectRecursive(); } secondIndirectRecursive() { //Logic firstIndirectRecursive(); }
範例:
為了顯示間接遞歸,我們使用以下程式來根據給定的輸入找出給定的數字是偶數還是奇數。
代碼:
import java.util.Scanner; public class IndirectRecursion { public static boolean oddNum(int i) { if (i<0) throw new IllegalArgumentException("Number is negative"); if(i == 0){ return false; } else { return evenNum(i-1); } } public static boolean evenNum(int i) { if (i<0) throw new IllegalArgumentException("Number is negative"); if(i == 0){ return true; } else { return oddNum(i-1); } } public static void main(String[] args) { Scanner inputNum = new Scanner(System.in); System.out.print("Give a number: "); int n = inputNum.nextInt(); if (evenNum(n)) System.out.println(n + " is even"); else System.out.println(n + " is odd"); inputNum.close(); } }
輸出:
這裡還有一些使用遞歸方法解決問題的範例。
如果 number3=number1+number2,即每個數字都是其前兩個數字總和,則稱一組「n」個數字位於斐波那契數列中。因此,序列總是從前兩位數字開始,如 0 和 1。第三個數字是 0 和 1 的和,結果是 1,第四個數字是 1 和 1 相加,結果是 2,序列繼續。
查看以下 Java 程式碼來產生斐波那契數列:
代碼:
public class FibonacciSeries{ static int num1=0,num2=1,num3=0; static void fibonacci(int n){ if(n>0){ num3 = num1 + num2; num1 = num2; num2 = num3; System.out.print(" "+num3); fibonacci(n-1); } } public static void main(String args[]){ int n=10; System.out.print(num1+" "+num2);//printing constant first two digits 0 and 1 fibonacci(n-2);//Since first two numbers are already done } }
輸出:
這裡前兩個數字被初始化為 0 和 1 並列印。變數“num1”、“num2”和“num3”用於產生所需的序列。變數「num3」是「num1」和「num2」相加得到的,數字透過打亂的方式向左移動一位,如程式碼所示。這裡遞歸呼叫函數“Fibonacci”,每次迭代時,“n”的值減 1。因此,一旦「n」達到值 0,遞迴就會退出。
這是一個經典的數學問題,有 3 個極點和「n」個不同大小的圓盤。謎題如下:
一開始,第一個桿子的圓盤排列方式是最大的圓盤位於桿的底部,最小的圓盤位於桿的頂部。目標是將這些圓盤從第一個極移動到第三個極,使圓盤保持與第一個極相同的位置。以下是移動這些磁碟時需要記住的一些條件:
以下是可用來解決該難題的Java程式碼:
代碼:
public class TowerOfHanoi { public static void main(String[] args) { int count = 3; tower(count, 'A', 'B', 'C'); } public static void tower(int first, char disk1, char temp, char disk2) { if (first == 1) { System.out.println("Disk 1 from " + disk1 + " to " + disk2); } else { tower(first - 1, disk1, disk2, temp); System.out.println("Disk " + first + " from " + disk1 + " to " + disk2); tower(first - 1, temp, disk1, disk2); } } }
輸出:
Here the variable “count” represents the number of discs to be used. The function “tower” is the recursive function used to move the discs from rod 1 to rod 3. A simple solution to this problem can be provided by considering 2 discs at first.
This same principle is applied for the “n” number of discs by moving (n-1)the disc from rod 1 to 2 and following similar steps as above.
Code:
package com.recursion; import java.util.Scanner; public class FactorialOfNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Which number factorial do you want?=>"); //taking input from the user int input = scanner.nextInt(); System.out.println("Factorial of " + input + "! is=>"+getMyFactorialNumber(input)); scanner.close(); } public static long getMyFactorialNumber(int inputNumber) { if (inputNumber == 1)//base condition return 1; return inputNumber * getMyFactorialNumber(inputNumber - 1);//recursive call } }
Output:
Code:
import java.util.Scanner; //ARMSTRONG number means sum of numbers of cubes equal to the number public class ArmstrongNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter any Number?=>"); // taking input from the user int input = scanner.nextInt(); //calling isArmstrongNumber() method and put in a variable double checkNumber=isArmstrongNumber(input); //checking the number if(input==checkNumber) { System.out.println(input+" is ARMSTRONG NUMBER"); } else { System.out.println(input+" not is ARMSTRONG NUMBER"); } scanner.close(); } static int remainderNumber; static double total = 0; public static double isArmstrongNumber(int inputNumber) { if (inputNumber > 0) { remainderNumber = inputNumber % 10;//separating digits total = total + Math.pow(remainderNumber, 3);//cubes sum isArmstrongNumber(inputNumber / 10);//recursive call } return total; } }
Output:
Code:
import java.util.Scanner; public class PalindromeNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter any Number=>"); // taking input from the user int input = scanner.nextInt(); int checkNumber = palindromeNumberOrNot(input,0); if (checkNumber == input) { System.out.println(input+" is a PALINDROME NUMBER"); } else { System.out.println(input+" is not a PALINDROME NUMBER"); } scanner.close(); } public static int palindromeNumberOrNot(int inputNumber,int baseNumber) { if (inputNumber == 0)// base case return baseNumber; baseNumber = (baseNumber * 10) + (inputNumber % 10);// getting the reverse of the number and stores in temp return palindromeNumberOrNot(inputNumber/10,baseNumber);//recursive call } }
Output:
Recursive functions are relatively simpler to code, but they are also not that efficient as compared to the other existing methods. Hence they are majorly used in cases where the time given for development is less and also where a significant pattern can be observed in the problem.
以上是Java 中的遞迴的詳細內容。更多資訊請關注PHP中文網其他相關文章!