+ 1

What is java equivalent code for factorial

help java

10th Apr 2017, 7:30 PM
Oluwagbenga
2 Answers
+ 5
for loops are probably the easier to understand: int num = 4; for(int i = num-1; i >1; i--) num *= i; num will now be its factorial. Though, I honestly prefer the recursive method : private static int factorial(int num){ if (num==1) return 1; return num * factorial (num-1); }
10th Apr 2017, 8:35 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
public class Program { public static void main(String[] args) { int x=5; int fact=1; while(x>0){ fact=fact*x; x--; } System.out.println(fact); } } It will give you a factorial of 5
10th Apr 2017, 7:38 PM
satyam saurav
satyam saurav - avatar