≡ Menu

Java Practice Assignment #5 – Recursive Factorial

As always, I’ll include my solution to the previous assignment before I give you the requirements for the next assignment. Here’s my video walk-through of assignment 4:

Click here to Download my Solution

Recursive Factorial Assignment

Since you have now learned about recursion in Java, now it’s time to put that knowledge to the test! Your job will be to implement a recursive method that will be able to calculate any given number’s factorial.

First off, if you don’t know what a factorial is, allow me to explain. A factorial is a calculation based on multiplying a given number by it’s decrementing values until you reach the number 1. The notation for this is a given number following by an exclamation mark. Let’s look at some examples, as they will make this explanation make sense:

2! = 2 x 1 = 2
3! = 3 x 2 x 1 = 6
4! = 4 x 3 x 2 x 1 = 24
5! = 5 x 4 x 3 x 2 x 1 = 120
6! = 6 x 5 x 4 x 3 x 2 x 1 = 720

Does that make sense to you? All we do is take the original number and then multiply it by the number lower than it by 1… rinse and repeat until we get to 1.

So if you remember the important aspects of a recursive algorithm, you’ll remember that you must have an ending point, and a constant progression towards that ending point.

Click here to View this Assignment on GitHub

And as always, here’s the GitHub Clone URI: https://github.com/tp02ga/JavaPracticeAssignment5.git

{ 4 comments… add one }

  • Bernd February 22, 2013, 12:01 pm

    Very simple assignment, no problem…

    But this arises a big Java problem, at least in my opinion:
    Why is there no such thing as “Numeric Overflow Error / Exception”??? I would expect this from any programming language!

    Dealing with “int” as your assignment is coded, starting from factorial(13) you get wrong results without notice, being sometimes nagative and constantly 0 from (34) onwards.

  • Robb G April 11, 2013, 11:04 pm

    Trevor, I just watched your video which shows your solution to this assignment(5) which included the use of an instance variable “total.” I had come up with the following which doesn’t require an instance variable and follows a little different logic than what you did. It passed your junit tests including the 5th one to make sure it’s recursive.

    public int factorial(int value)
    if (value==1) return 1;
    return (value*factorial(value-1));

  • wessley sang May 31, 2013, 8:19 am

    please assist on this.:using queues to rervese string of characters in java

Leave a Comment