1. Member
Join Date
Feb 2012
Posts
57
Rep Power
0

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....

Java 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);
int n = in.nextInt();
System.out.println(factorial(n));
}
public static int factorial(int n)
{
while (n <= 1)
{
n = (n-1) * n;
n--;

}
return factorial(n);
}
}```

2. 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.
Last edited by Norm; 03-19-2012 at 10:42 PM.

3. 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: Problem in while conditions

db

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•