English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, você aprenderá a usar funções recursivas em Java para encontrar e exibir o fatorial de um número.
O fatorial de um número positivo n é dado pela seguinte expressão:
o fatorial de n (n!) = 1 * 2 * 3 * 4 * ... * n
O fatorial de números negativos não existe. O fatorial de 0 é1.
Neste exemplo, você aprenderá a usar recursão para encontrar o fatorial de um número. Acesse esta página para saber comoUsar loop para encontrar o fatorial de um número.
public class Factorial { public static void main(String[] args) { int num = 6; long factorial = multiplyNumbers(num); System.out.println("") + num + "factorial = " + factorial); } public static long multiplyNumbers(int num { if (num >= 1) return num * multiplyNumbers(num - 1); else return 1; } }
When running the program, the output is:
6factorial = 720
Initially, multiplyNumbers() is called from the main() function, with6is passed as a parameter.
because6greater than or equal to1so6multiplied by the result of multiplyNumbers(), where5 (num -1). Because it is called from the same function, it is a recursive call.
In each recursive call, the value of the parameter num is reduced1until num is less than1.
When the value num is less than1there will be no recursive calls.
Each recursive call returns to us:
6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720