Friday, September 15, 2023

 Find factorial of a number



The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers from 1 to n. Mathematically, it is expressed as: n! = 1 * 2 * 3 * ... * (n-1) * n.

In Java we can find factorial of a number in both iterative and recursive way.


Finding factorial of a number in Java - iterative way

To find the factorial of a number in Java (iterative), we can use a loop to multiply the numbers from 1 to n.
public int factIterative(int n) {
int factorial = 1; // Initialize factorial as 1

// Calculate factorial using a loop
for(int i = 1; i <= n; i++) {
factorial *= i;
}

return factorial;
}


Finding factorial of a number in Java - recursive way

In this program, we call the recursive method passing the n - 1 and multiplying with the current n in each turn and we do that until n becomes 1.

public int fact(int n) {
if (n == 1) { // BASE CASE
return n;
}

return n * fact(n - 1);
}







No comments:

Post a Comment