# Computing Factorials

• 03-19-2012, 09:56 PM
jmscarlet9
Computing Factorials
Hey everyone,
I need help with my Intro to Programming classes. Here is the assignment:

Given a positive number n, the factorial of that number, denoted n!, is equal to 1 × 2 × ... × (n-1) × n. It can also be computed recursively: n! = n × (n-1)!, for all n greater than or equal to zero.

For example,

3! = 3 × 2!
= 3 × 2 × 1!
= 3 × 2 × 1
= 3 × 2
= 6
By convention, 0! is 1.

Here's the code I have so far....I think I'm way off....

Code:

```import java.util.Scanner; public class ComputeFact {         /**                 A method to compute n factorial (n!) recursively                 @param n a number >= 0                 @return the value of n!         */         public static void main(String[]args)         {                 Scanner in = new Scanner(System.in);                 System.out.print("Please enter an interger: ");                 int n = in.nextInt();                 System.out.println(factorial(n));         }         public static int factorial(int n)         {                 //your work here                 while (n <= 1)                 {                         n = (n-1) * n;                         n--;                 }                 return factorial(n);         } }```
• 03-19-2012, 10:36 PM
Norm
Re: Computing Factorials
What output does the program print?

Try working out the logic and how to generate the factorial using a piece of paper before trying to write the code.

Look at the condition in the while statement.
• 03-20-2012, 01:38 AM
DarrylBurke
Re: Computing Factorials
davie89, don't hijack another poster's thread -- get your own, they're free. Your post and the response have been moved to a new thread: http://www.java-forums.org/new-java/...onditions.html

db