Advertisements
How to calculate factorial of a given number?
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Factorial { public static void main(String args[]) throws IOException { System.out.println("Please Input Any Number"); int num = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String data = (String) br.readLine(); num = Integer.parseInt(data); int result = num; for (int i = 1; i < num; i++) { result = result*i; } System.out.println(result); } }
Description: - Factorial of any number n is represented by !n and is equal to n(n-1)(n-2)(n-3)?.1. BufferReader () is used for user input.BufferReader consider inputted value as String so for int value you have to use Integer.parseInt(). For loop from 1 to num-1 calculating the factorial value of num as result=result*i. Initial value of result is num.
Explanation : Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. for example, 3 factorial is 1Ã?2Ã?3, or 6. Here is how a factorial can be computed by use of a recursive method