This question already has answers here:
Understanding how recursive functions work
(18 answers)
Closed 7 years ago.
I have the following program
public static int doSomething(int num){
if(Math.abs(num) > 9){
return (1 + doSomething( num / 10));
}
else{
return 1;
}
}
public static void main(String[] args){
System.out.println(doSomething(333));
}
This is how I understand it. If the number is 333.
333 / 10 gives me 33. Since 33 > 9 it runs the recursive loop again giving me 3.
After 3 it enters the else condition.
I don't understand why it prints 3 as answer.
I am new to java so still trying to understand the basics.
I don't believe the question is a duplicate. My question is much simpler being a beginner to java. Also the question I believe is using javascript not java.
Look, what will return doSomething() if Math.abs(num) < 9? 1? yes you are right. Ok lets start.
doSomething(333) => 1 + doSomething(33) // 33 not less than 9
=> 1 + (1 + doSomething(3)) // now 3 is less than 9
=> 1 + (1 + {1})
=> 3
The recursion is not on 1 + 33, but on 33 only, so it's:
doSomething(333)
= 1 + doSomething(33)
= 1 + 1 + doSomething(3)
= 1 + 1 + 1
= 3
Related
This question already has answers here:
Understanding recursion [closed]
(20 answers)
In a recursive statment, how does java store the past values?
(3 answers)
Reversing a String with Recursion in Java
(17 answers)
How are the numbers stored, called, and added in this short recursion example?
(3 answers)
Closed 3 years ago.
I'm attempting to create a method that will calculate the sum of a an integer, as the integer is broken down in to single integers.
E.g. 2546 becomes 2, 5, 4, 6. Then I plus those all together.
2 + 5 + 4 + 6 = 17
The method will run recursively.
I'd made this program non-recursively, but in that one, I had a variable to store a sum of the calculation.
public static int calcSum(int n){
if (n>0)
return ((n%10) + calcSum(n/10));
else
return 0;
}
The program works, I just don't understand how the sum is stored.
The sum is not stored in any variable (unless the caller of the recursive method will store the result in some variable).
The recursive method returns the sum to its caller without storing it in a variable:
return ((n%10) + calcSum(n/10));
or returns 0 if the input is 0.
calcSum(2546) returns 6 + calcSum(254)
calcSum(254) returns 4 + calcSum(25)
calcSum(25) returns 5 + calcSum(2)
calcSum(2) returns 2 + calcSum(0)
calSum(0) returns 0
so when the recursion unwinds:
calcSum(2) returns 2 + 0 == 2
calcSum(25) returns 5 + 2 == 7
calcSum(254) returns 4 + 7 == 11
and finally
calcSum(2546) returns 6 + 11 == 17
This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 3 years ago.
I don't understand the following recursive code.
int func(int num){
if(num == 1){
return 1;
}
else{
return (func(num-1) + num));
}
}
public static void main(String[] args) {
System.out.println(func(100));
}
So the output is 5050.
I don't understand why that is. Can someone explain to me the working of the code?
Let's do it again with 3. Add system.out at every line.
The thing is when a function call happen, current function execution stops until the new function end and gives its result.
This is the program stack: the list of functions that wait for a subfunction to terminate.
With the code you provide, you will have a stack of 100 "func" calls, then the last call contain num == 1, because you have decremented 99 times 100.
After that all of the 100 func will return, each with the + num addition.
Ok, so let's analyze from the beginning the behaviour of your code step by step:
First of all, you call func(100)
100 is different than 1 so the first 'if' is skipped, the function "func(100)" returns
100 + func(99)
99 is different than 1 so the first 'if' is skipped, the function "func(99)" returns
99 + func(98)
so for the moment "func(100)" returns 100 + 99 + func(98)
same steps as before for func(97) until func(2)
so your function "func(100)" returns 100 + 99 + 98 + 97 + ..... + 2 + func(1)
func(1) 'if' this time is not ignored so func(1) returns 1
now you have func(100) = 100 + 99 + 98 + ..... + 2 + 1 which is the sum of the first 100 positive integers which is 5050
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Implementation of fibonacci in Java:
public class Fibonacci {
private int fibonacci(int n){
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
private void test(){
System.out.println(fibonacci(4));
}
public static void main(String[] args) {
Fibonacci test = new Fibonacci();
test.test();
}
}
Using Oracle Java 8 on Ubuntu, it prints out 3 in Eclipse. But I was expecting 5:
fibonacci(4)
fibonacci(3) fibonacci(2)
fibonacci(2) fibonacci(1) fibonacci(1) fibonacci(0)
fibonacci(1) fibonacci(0) 1 1 1
1 1
So then what's wrong with my Java implementation?
Your fibonacci(int n) in Java will return 0 for n=0. You want to always return 1 for n<2. Replace:
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
with
return n < 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
As it currently stands, the following is evaluated: (f is short for fibonacci)
f(4)
f(3)+f(2)
(f(1)+f(2))+(f(0)+f(1))
(1+(f(0)+f(1)))+(0+1)
(1+0+1)+(0+1)
2+1
3
The following should occur:
f(4)
f(3)+f(2)
(f(1)+f(2))+(f(0)+f(1))
(1+(f(1)+f(1)))+(1+1)
(1+1+1)+(1+1)
3+2
5
This has nothing to do with the language.
The first returns the sequence 0 1 1 2 3 5 8 13 ...
The second returns the sequence 1 1 2 3 5 8 13 ...
It's up to you to decide which sequence you want.
This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.
is my first time here so i dont know exactly how it works, so sorry for the mistakes.
What's the result from this function, when we give as "aktueller Parameter" the number 3?
(The original text:
Welches Ergebnis liefert diese Methode, wenn bei einem Aufruf als aktueller Parameter
der Wert 3 übergeben wird?
Im studying in German, so i dont really know the english terms :/ )
public int m(int p)
{
int result;
if (p == 0)
{
result = 0;
}
else
{
result = 3*p + m(p-1);
}
return result;
}
I have already tried it and the answer is 18, but when im trying to do it without any program the answer i find is 15:
result = 3 * 3 + 3(3-1);
Can someone please explain me why is 18 and not 15? Im assuming that i am making something wrong.
Thank you in advance.
Let's break down this recursive call:
With m(3), p isn't 0, so we return 3*3 + m(2);.
3*3 + (m(2))
With m(2), p isn't 0, so we return 3*2 + m(1);.
3*3 + (3*2 + m(1))
With m(1), p isn't 0, so we return 3*1 + m(0);.
3*3 + (3*2 + (3*1 + m(0))
With m(0), p is 0, so we return 0. Then the recursive call stack unwinds.
3*3 + (3*2 + (3*1 + (0)) =
9 + (6 + (3 + 0)) =
9 + (6 + 3) =
9 + 9 =
18
When you see m(p-1), that means that you're calling the function m again from inside itself, which is called recursion.
Essentially, the arithmetic it's doing is 3*3+3*2+3*1 = 18.
Due to recursive code.Please c the strack trace
When you pass the p value as 3,the function interact as below :
result = 3*p + m(p-1); // 3*3 + m(2) = 9
// 3*2 + m(1) = 6
// 3*1 + m(0) = 3
-------
18
// Original argument is 3
3*3 + m(3-1) // Step #1 New argument is 3 - 1
3*2 + m(2-1) // Step #2 New argument is 2 - 1
3*1 + m(1-1) // Step #3 New argument is 1 - 1
// p == 0 Return 0
3*1 + 0 = 3 // Step #4 Return 3
3*2 + 3 = 6 + 3 = 9 // Step #5 Return 9
3*3 + 9 = 9 + 9 = 18 // Step #6 Return 18, which is the final value
Here is how I like to work on recursive functions, and it a personal preference. Start at the top, and put together the known values, then write the function on the side, in this case we simply add it. Then, on the next line, write the known values again (this time, one of them is one less (2, rather than 3), and write the function with the new arguments to the right of it (we're once again adding), and so on. I work from top to bottom.
I then show the results on the right side and work back up. So, I don't write the results right away.