使用递归查找数字阶乘的 Java 程序
在本文中,我们将了解如何使用递归查找数字的阶乘。数字的阶乘是它本身与其每个较小数字的乘积。阶乘是应用于大于零的自然数的函数。阶乘函数的符号是在数字后面加上一个感叹号,例如:5!
递归函数是一个多次调用自身的函数,直到满足特定条件。递归是重复以自相似方式的项目的过程。在编程语言中,如果程序允许您在同一个函数内部调用一个函数,则称为该函数的递归调用。
许多编程语言通过栈来实现递归。通常,每当一个函数(调用方)调用另一个函数(被调用方)或自身作为被调用方时,调用方函数都会将执行控制权转移到被调用方。此转移过程可能还涉及一些数据从调用方传递到被调用方。
下面是相同内容的演示 -
输入
假设我们的输入是 -
Enter the number : 7
输出
所需的输出将是 -
The factorial of 7 is 5040
算法
Step 1 - START Step 2 - Declare an integer values namely ‘my_input’ and a long value namely ‘my_result’ Step 3 - Read the required values from the user/ define the values Step 4 - A recursive function ‘factorial’ is defined which takes an integer as input and returns the product of the input and its previous number until the input value is reduced to 1. Step 5 - The recursive function is called and the value ‘my_input’ is passed to it. Store the return value Step 6 - Display the result Step 7 - Stop
示例 1
这里,输入是根据提示由用户输入的。您可以在我们的编码练习工具 中实时尝试此示例。
import java.util.Scanner; public class Factorial { public static void main(String[] args) { int my_input ; long my_result; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the number : "); my_input = my_scanner.nextInt(); my_result = factorial(my_input); System.out.println("The factorial of " + my_input + " is " + my_result); } public static long factorial(int my_input){ if (my_input >= 1) return my_input * factorial(my_input - 1); else return 1; } }
输出
Required packages have been imported A reader object has been defined Enter the number : 7 The factorial of 7 is 5040
示例 2
这里,整数已预先定义,其值在控制台上被访问和显示。
public class Factorial { public static void main(String[] args) { int my_input ; long my_result; my_input = 7; System.out.println("The number is defined as " +my_input); my_result = factorial(my_input); System.out.println("The factorial of " + my_input + " is " + my_result); } public static long factorial(int my_input){ if (my_input >= 1) return my_input * factorial(my_input - 1); else return 1; } }
输出
The number is defined as 7 The factorial of 7 is 5040
广告