Results 1 to 3 of 3
  1. #1
    jmscarlet9 is offline Member
    Join Date
    Feb 2012
    Posts
    57
    Rep Power
    0

    Default 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);
    		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);
    	}
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,331
    Rep Power
    25

    Default 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 09:42 PM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default 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
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Computing bytes
    By captainjack in forum New To Java
    Replies: 5
    Last Post: 10-28-2011, 01:22 AM
  2. Replies: 8
    Last Post: 03-10-2011, 03:16 AM
  3. computing hour & Salary
    By arshesander in forum New To Java
    Replies: 4
    Last Post: 08-07-2009, 10:17 PM
  4. Factorials help
    By jhering1986 in forum New To Java
    Replies: 3
    Last Post: 04-06-2009, 01:50 AM
  5. Computing the sum
    By Limuh in forum New To Java
    Replies: 3
    Last Post: 08-13-2008, 06:00 AM

Posting Permissions

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