+ 1
What is java equivalent code for factorial
help java
2 Respostas
+ 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);
}
+ 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