0
import java.util.*;

public class factorial
{
	public static void main(String[]args)
	{
		int m,f,n;
		System.out.println("Factorial Solver");
		System.out.println("Enter a number");
		Scanner sc = new Scanner(System.in);
     	n = sc.nextInt();
     	m = 1;
     	f = 1;
     	f = f * m;
     	while (m != n)
     	{
     		m = m + 1;
     	}
     	f = f * m;
     	System.out.println(f);
 
	}
}

Whenever I run it, it does not come out with the factorial. It just prints out the inputted value most of the time. Why is that?

5
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by nomemory
0

technically, no

but if it doesn't work using a while loop, it doesn't hurt to try using a for loop

0

use for loop. It will be conceptually easier.

int F =5;
int R = 1;
for i = F to i >1 ; i--
{
    R equals R times F;
    F equals F minus 1;
}
0
public class FactorialFinder {

	public static void main(String[] args) {
		int counter = 5;
		int number = counter;
		long factorial = counter;
		while (counter > 1)
			factorial *= --counter;
		System.out.println("Factorial of " + number + " is " + factorial);
	}
}

SNIP

Edited by happygeek: spam deleted

0
public class Factorial {
    public static int result=1;
    
    public static void getFactorial(int n){
	if(n>0){
	    result*=(n--);
	    getFactorial(n);
	}
    }
    
    public static void main(String args[]){
	getFactorial(4);
	System.out.println(result);
    }
}

You can also try this solution if your number is positive.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.