In this article, we will learn multiple approaches to finding the factorial of a number in Java Programming. Before moving to the code part lets us first understand what is Factorial and how to calculate it.
What is the Factorial of a Number?
Factorial is a mathematical operation that is used to calculate the product of all positive integers from 1 to a given positive integer n.
It is denoted by the symbol "!" and is defined as follows:
- n! = n x (n-1) x (n-2) x ... x 3 x 2 x 1
For example, the factorial of 5 is calculated as:
- 5! = 5 x 4 x 3 x 2 x 1 = 120
- The factorial of 0 is defined to be 1 by convention, that is: 0! = 1
We can find the factorial of a number using the following approaches:
Find Factorial using for loop.
In this approach, we use a for loop to multiply each number from 1 to n, where n is the number for which we need to find the factorial.
Java Code:
//Java code to find factroil of a number using for loop import java.util.Scanner; public class HelloWrold { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int n = input.nextInt(); int factorial = 1; for (int i = 1; i <= n; i++) { factorial *= i; } System.out.println("Factorial of " + n + " is " + factorial); } }
Enter a number: 5
Factorial of 5 is 120
- Time Complexity: O(n)
- Space Complexity: O(1)
Find Factorial using Recursion.
//Java code to find factroil of a number using Recursion import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int n = input.nextInt(); int factorial = fact(n); System.out.println("Factorial of " + n + " is " + factorial); } public static int fact(int n) { if (n == 0) { return 1; } return n * fact(n - 1); } }
Enter a number: 5
Factorial of 5 is 120
- Time Complexity: O(n)
- Space Complexity: O(n)
Find Factorial using a while loop.
//Java code to find factroil of a number using while loop import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int n = input.nextInt(); int factorial = 1; int i = 1; while (i <= n) { factorial *= i; i++; } System.out.println("Factorial of " + n + " is " + factorial); } }
Enter a number: 10
Factorial of 5 is 3628800
- Time Complexity: O(n)
- Space Complexity: O(1)
No comments:
Post a Comment