Results 1 to 6 of 6

Thread: Help with psuodocode

  1. #1
    Join Date
    Dec 2004
    Posts
    476
    Rep Power
    0

    Exclamation Help with psuodocode

    could somone please solve this problem

    N factorial (N!) is defined as the following series of numbers:
    N! = N*(N-1) * (N-2) * (N-3) * ..........*1
    CALCULATE a psuodocode to compute N! and ouput N and N!.
    N! should only be calculated if N is greater than 0. If not output an appropriate statement.

    As far a s i see it this is a dowhile program.
    WHY PAY WHEN YOU CAN GET IT FREE!!!!!

  2. #2
    Join Date
    Apr 2005
    Posts
    1,333
    Rep Power
    0

    Default

    Not really, can also be done with a For..Next as well:

    INPUT N
    IF N > 0 THEN
    NF = N
    FOR I = (N - 1) TO 1 STEP -1
    NF = NF * I
    NEXT
    ELSE
    PRINT "ERROR: N is not positive integer."
    END IF
    The fox was probably right - they could have been sour grapes.

  3. #3
    Join Date
    May 2005
    Posts
    59
    Rep Power
    0

    Default

    You could also do it recursively (which would be faster with large numbers, maybe) not sure how it looks in pseudocode but it is probably:
    factorial(n) = n * factorial(n-1)
    factorial(0) = 1

    In java it is:
    int factorial(int n)
    {
    if(n < 1) // base case
    return 1;
    else
    return n * factorial(n-1); // recursive call
    }
    Hope that helps. Note the check for 0 and -ve.
    "I don't believe in astrology; I'm a Capricorn and we're skeptical."

  4. #4
    Join Date
    Apr 2005
    Posts
    1,333
    Rep Power
    0

    Default

    Yes, but I don't see what will happen when factorial(N - 1) evaluates to 0 or less? Maybe I miss something?

    I must admit that java is not my strong point.
    The fox was probably right - they could have been sour grapes.

  5. #5
    Join Date
    May 2005
    Posts
    59
    Rep Power
    0

    Default

    When factorial(N - 1) evaluates to 0 (it can't be -ve) the recursion ends. The base case is the 'flag' to end the recursion.
    NB:
    if N-1 = 0 then 0 is passed back into the method (factorial(0)) then the condition if(n < 1) is evaluated and the method returns 1 therby ending the recursion.
    when n<= 1 then n! = 1 and

    5! = 5(4!) which is similar to n * factorial(n-1)
    Last edited by jagfun; Dec 18, 2005 at 02:16 PM. Reason: clarifying the math
    "I don't believe in astrology; I'm a Capricorn and we're skeptical."

  6. #6
    Join Date
    Apr 2005
    Posts
    1,333
    Rep Power
    0

    Default

    Oh I see. I don't know anything about that kind of routine.
    The fox was probably right - they could have been sour grapes.

Posting Permissions

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