Solved

factorial example challenge

Posted on 2016-09-09
10
90 Views
Last Modified: 2016-09-11
factorial



Hi,

I am working on below challenge
http://codingbat.com/prob/p154669

Psedo code:
1. return the n multiplied by same method call with n-1
I wrote my code as below

public int factorial(int n) {
  return n * factorial(n-1);
}

Open in new window




I am failing below tests

Expected      Run            
factorial(1) → 1      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(2) → 2      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(3) → 6      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(4) → 24      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(5) → 120      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(6) → 720      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(7) → 5040      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(8) → 40320      Exception:java.lang.StackOverflowError (line number:2)      X      
factorial(12) → 479001600      Exception:java.lang.StackOverflowError (line number:2)      X      
other tests
X      

How to improve/modify my design, code and any other alternate approaches. please advise
0
Comment
Question by:gudii9
  • 4
  • 2
  • 2
  • +1
10 Comments
 
LVL 14

Accepted Solution

by:
CPColin earned 250 total points
ID: 41791960
You need to have a "base case" where the function returns some value without calling itself again. Otherwise, the function calls itself forever and overflows your stack.
0
 
LVL 15

Assisted Solution

by:gurpsbassi
gurpsbassi earned 125 total points
ID: 41791963
You are missing base case for recursion.
0
 
LVL 12

Assisted Solution

by:tel2
tel2 earned 125 total points
ID: 41792078
Hi gudii9,

Are you aware that CodingBat has hints for thing like this?

If you go to the link you supplied:
    http://codingbat.com/prob/p154669
then click the "Show Hint" button to the right of the "Go" button, it will give you this help:
Hint:
First, detect the "base case", a case so simple that the answer can be returned immediately (here when n==1). Otherwise make a recursive call of factorial(n-1) (towards the base case). Assume the recursive call returns a correct value, and fix that value up to make our result.
Doing that should mean that you don't have to ask so many questions at EE.

And if you still can't work it out, and just want to see the solution, then you can click the "Show Solution" button, and a solution should appear on the right of the page, but make sure you read the comments in the code, to get a better understanding.
0
 
LVL 7

Author Comment

by:gudii9
ID: 41792177
public int factorial(int n) {
  if(n==1){
    return 1;
  }
  return n * factorial(n-1);
}

Open in new window


like above?
Above passed all the tests.

You need to have a "base case" where the function returns some value without calling itself again. Otherwise, the function calls itself forever and overflows your stack.

what is base case. why we need it?
why does functions calls itself forever without base case?
please advise
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 7

Author Comment

by:gudii9
ID: 41792178
http://introcs.cs.princeton.edu/java/23recursion/

I am reading more at above link as well
0
 
LVL 7

Author Comment

by:gudii9
ID: 41792179
any improvements or alternate approaches?
0
 
LVL 12

Expert Comment

by:tel2
ID: 41792195
Hi gudii9,

"what is base case. why we need it?
The answer to those questions are in my post above.  Did you read it?

"why does functions calls itself forever without base case?
Because there will be nothing to stop it from looping if your function simply calls itself regardless of the argument passed to it.

Well, if you consider making it shorter to be an improvement, you could do something like this:
    return n == 1 ? 1 : factorial(n-1);
but many people will find that less readable.
Are you familiar with the above short-hand alternative to the "if...else..." syntax?
0
 
LVL 14

Expert Comment

by:CPColin
ID: 41792219
what is base case. why we need it?
I answered that in the same sentence as I introduced the term.
why does functions calls itself forever without base case?
Because that's what happens when a recursive function has no base case, by definition!
0
 
LVL 7

Author Comment

by:gudii9
ID: 41793640
   return n == 1 ? 1 : factorial(n-1);
but many people will find that less readable.
Are you familiar with the above short-hand alternative to the "if...else..." syntax?
yes. I am. I like above approach too
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
This is about my first experience with programming Arduino.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now