First Code: a = 5
if (a==0)
return 1;
return a * xample(a-1);
My tracing:
5==0 FALSE
skip return 1
return 5 * xample(5-1)
so, a = 4
go back inside the method
4==0 FALSE
skip return 1
return 5 * xample(4-1)
so, a = 3
go back inside the method
3==0 FALSE
skip return 1
return 5 * xample(3-1)
so, a = 2
go back inside the method
2==0 FALSE
skip return 1
return 5 * xample(2-1)
so, a = 1
go back inside the method
1==0 FALSE
skip return 1
return 5 * xample(1-1)
so, a = 0
go back inside the method
0==0 TRUE
return 1
so last value is 1, how come the real last value is 120?
Second Code: a = 5
if (a<1)
return 1;
else
return a + xample(a/5);
how come the answer is 7?
Third Code: a = 5
a--;
if (a>0)
{
xample(a);
}
return a;
How come the answer is 4???
In the following code :
if (a==0)
return 1;
return a * xample(a-1);
If a is 5 :
return 5 * xample (5 - 1) =
5 * 4 * xample (4 - 1) =
5 * 4 * 3 * xample (3 - 1) =
5 * 4 * 3 * 2 * xample (2 - 1) =
5 * 4 * 3 * 2 * 1 * xample (1 - 1) =
5 * 4 * 3 * 2 * 1 * 1 = 120
Related
why isn't the loop starting again with different value of a other than 1.
package com.company;
import java.util.Scanner;
public class ForDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("ENTER A NUMBER: ");
int b = sc.nextInt();
int a;
for(a=1 ;a<11;a=a+1)
for(b=b;b<16;b=b+1)
System.out.println(b + " * " + a + " = " + b*a);
}
}
output:
ENTER A NUMBER: 1
1 * 1 = 1
2 * 1 = 2
3 * 1 = 3
4 * 1 = 4
5 * 1 = 5
6 * 1 = 6
7 * 1 = 7
8 * 1 = 8
9 * 1 = 9
10 * 1 = 10
11 * 1 = 11
12 * 1 = 12
13 * 1 = 13
14 * 1 = 14 here it terminates!
required output:
1 * 1 = 1
2 * 1 = 2
3 * 1 = 3
4 * 1 = 4
5 * 1 = 5
6 * 1 = 6
7 * 1 = 7
8 * 1 = 8
9 * 1 = 9
10 * 1 = 10
11 * 1 = 11
12 * 1 = 12
13 * 1 = 13
14 * 1 = 14
15 * 1 = 15
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 8
5 * 2 = 10
6 * 2 = 12
7 * 2 = 14
8 * 2 = 16
9 * 2 = 18
10 * 2 = 20
11 * 2 = 22
12 * 2 = 24
13 * 2 = 26
14 * 2 = 28
15 * 2 = 30 and so on....
You are doing this: b=b. So do this:
for(a=1 ;a<11;a=a+1)
for(b=1;b<16;b=b+1) // change here!!
System.out.println(b + " * " + a + " = " + b*a);
Simply assign your input variable (x) at the starting of the inner loop as below will solve your problem.
Till now you were initialized b as the last value of the previous iteration that is why your inner loop is not executed after the first iteration.
public class Simple {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println();
System.out.print("ENTER A NUMBER: ");
int x = sc.nextInt(); // take input as x
for(int a=1 ;a<11;a++) {
for (int b = x; b < 16; b = b + 1) { // initialize b with input variable(x)
System.out.println(b + " * " + a + " = " + b * a);
}
}
}
}
I created two recursive methods to calculate factorial as follows:
private int fact1(int n) {
if (n == 0 || n == 1)
return 1;
return n * fact1(--n);
}
private int fact2(int n) {
if (n == 0 || n == 1)
return 1;
return fact2(--n) * n;
}
When I call fact1(4) it returns 24. When I call fact2(4) it returns 6 (EDIT: is not returning 18 but 6). I know the second method is making 3 * 2 * 1, but I don't understand why not 4 * 3 * 2 * 1.
The same happens if I change the return to
//fact3(4) returns 60.
return (n + 1) * fact3(--n); // wrong
//fact4(4) returns 24
return fact4(--n) * (n + 1); // works
Why is the method exhibiting this behavior??
The question is about the different behaviour. I know n * fact(n-1) is the better way to solve it.
Can someone help me to understand the evaluation of this expression? Thanks!
It all comes down to the difference between these expressions:
return n * f(--n);
return f(--n) * n;
When n = 4, these expressions are evaluated like this:
return 4 * f(3);
return f(3) * 3;
Because the moment --n is evaluated, the value of n is decreased by 1.
This is how the prefix -- operator works.
It might help to recursively evaluate the entire expressions by hand. The first one:
// first
return 4 * f(3);
return 4 * 3 * f(2);
return 4 * 3 * 2 * f(1);
return 4 * 3 * 2 * 1;
// second
return f(3) * 3;
return f(2) * 2 * 3;
return f(1) * 1 * 2 * 3;
return 1 * 1 * 2 * 3;
On a related note, guess how this will be evaluated:
return f(n--) * n;
It will be:
return f(4) * 3;
Because here the postfix -- operator is used: the -1 decrement will be applied after the evaluation of n in f(...).
Here is I have a factorial code using recursion.
class Factorial
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt(args[0])));
}
private int fact(int num)
{
int result;
if(num == 1)
return 1;
result = fact(num - 1) * num;
return result;
}
}
Now to run this program, I did this
D:\>java Factorial 3
Now according to the logic when it enters the fact function, where num = 3, so it will skip to
result = fact(num - 1) * num;
Here it will become
result = fact(3 - 1) * num;
i.e. result = fact(2) * num;
In this step, I am little confused Does it execute whole step i.e.
result = fact(num - 1) * num;
or just the fact(num - 1)
According to the logic, what it should do is call the fact function. So, the control of the program again reaches to the start of the fact function where num = 2. It will again skip to
result = fact(num - 1) * num;
So, it will become
result = fact(2 - 1) * num;
i.e. result = fact(1) * num;
Now again, it should call the fact function without executing the whole syntax & again reaches to the start of the fact method where num = 1. This time num == 1 will be matched & 1 will be returned. Now it will return to
result = fact(num - 1) * num;
So, it will become
result = fact(1 - 1) * num;
i.e. result = fact(0) * num;
Now what will happen next ?
Am I going right ? If not what will be the correction ?
I dont clearly understand the flow of this recursion program.
So, it will become
result = fact(1 - 1) * num;
Nope. For num = 2,
result = fact(num - 1) * num;
becomes
result = 1 * num; // i.e. 1 * 2
fact returns a value, which means the entire call has to be replace with that value.
Not sure why you would even think num changes at all. You have no num = ... in your code.
I added some trace into the program. Execute it and see the output. Should be easy to follow.
package snippet;
class Factorial {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt("5")));
}
private int fact(int num) {
int result;
if (num == 1)
return 1;
result = fact(num - 1) * num;
System.out.println("fact(" + num + ") = " + result + " = fact(" + (num - 1) + ") * " + num);
return result;
}
}
fact(2) = 2 = fact(1) * 2
fact(3) = 6 = fact(2) * 3
fact(4) = 24 = fact(3) * 4
fact(5) = 120 = fact(4) * 5
120
Your logic is right but you have made 3 basic errors.
if we take your example;
First you run the program
D:\>java Factorial 3
then you have your first mistake because according to the logic all "num" have to be replaced by "3". So you get:
result = fact(3 - 1) * 3;
ie:
result = fact(2)*3;
then we have the second mistake because according to the definition of fact(num),
fact(2) = fact(2-1)*2
so we actually have
result = (fact(2-1)*2)*3
which is evaluated in
result = (fact(1)*2)*3
and here stand the third mistake because again according to fact(num) definition : fact(1) = 1 and not fact(1) = fact(1-1)*1
so we finally have:
result = ((1)*2)*3
To be more explicit if you follow all call sequence in the debugger you 'll have something like this( I put between brackets the value of the variable):
private int fact(num{3})
{
int result;
if(num{3}== 1)
return 1;
result = fact(num{3} - 1) * num{3};
private int fact(num{3-1})
{
int result;
if(num{3-1}== 1)
result = fact(num{3-1} - 1) * num{3-1};
private int fact(num{3-1-1})
{
int result;
if(num{3-1-1}== 1)
return 1;
}
return result{1*{3-1}};
}
return result{{1*{3-1}}*3};
}
Unless we hit the stop condition:
fact(num) = fact(num - 1) * num;
Therefore:
fact(3) = fact(3 - 1) * 3;
Keeping in mind that fact(1) = 1 (from the if statement early in the fact() method):
fact(3) = fact(2) * 3;
fact(2) = fact(1) * 2;
fact(1) = 1;
Replacing each element:
fact(3) = 1 * 2 * 3;
The recursion is used to repeatedly dive deeper into the process until a stop condition is encountered - in this case when num = 1.
The call f.fact(3) is expanding through the following steps:
1. result = fact(3 - 1) * 3 = fact(2) * 3
2. result = (fact(2 - 1) * 2) * 3 = (fact(1) * 2) * 3
3. result = 1 * 2 * 3 because fact(1) returns 1.
Your implementation is correct, But it will never reach fact(1-1) * 1 state ,as you return from method at if(num == 1).
num variable is limited to scope of method parameter. So for every call to fact method num variable is assigned a new value (i.e. num-1) and which is limited to that parameter scope only. So when fact(num-1) returns , value of num will be the original value and not the num-1.
The flow of your example is like this
step 1. fact(3)*3; //calling the function with num value 3
step 2. fact(2)*2; //calling fact() method again with num=2
step 3. fact(1)*1; //now num == 1 will be matched & 1 will be returned.
i. e.,
1 * 1 = 1; //now, steps 2 and 1 will be performed respectively
step 2. 1 * 2 = 2;
step 1. 2 * 3 = 6;
So, the final answer will be 6
Note: In step 3, the value is returned, so it will not again call this result = fact(0) * num; //which you have mentioned in question.
I've chosen Java for this case because the language is simple enough for anyone to translate.
What would be the mathematical algorithm to determine the number of fruit required on the bottom line to stack X number of fruits in a pattern like this? (ignoring power of 2's, which I stack in a square)
* 1
* 2 3 = 2
*
* 1 2
* 3 4 5 = 3
*
* 1
* 2 3
* 4 5 6 = 3
*
* 1 2 3
* 4 5 6 7 = 4
*
* 1 2
* 3 4 5
* 6 7 8 9 = 4
*
* 1
* 2 3
* 4 5 6
* 7 8 9 X = 4
*
* 1 2 3
* 3 4 5 6
* 7 8 9 X 1 = 5
Initially I thought it'd be easy, but as the numbers got higher I'm starting to think it's more of a factorial.
Edit: Adding in the code translated from answer provided below by #templatetypedef
private int _getBottomLineCount() {
double insideSquareRoot = (8 * numberOfApples) +1;
double squareRoot = Math.sqrt(insideSquareRoot);
double val = (squareRoot -1) /2;
return (int) Math.ceil(val); // Round it up to nearest whole number
}
The number of fruit in a pyramid of height n is given by the nth triangular number, given by the equation
Tn = n(n + 1) / 2
For example, a pyramid of height 2 holds 2(2 + 1) / 2 = 3 fruit. A pyramid of height 4 holds 4(4 + 1) / 2 = 10 fruit.
If you have k fruit to put into a stack, you're looking for the smallest number n such that Tn ≥ k. You can solve for this directly:
Tn = k
n(n + 1) / 2 = k
n2 + n = 2k
n2 + n - 2k = 0
Using the quadratic formula gives
n = (-1 ±√(1 + 8k)) / 2
The negative root here can be ignored, so your number n should be given by
n = (√(8k + 1) - 1) / 2
This number might be not be an integer, in which case you want to round up.
Let's try some examples. Suppose that you have 9 fruit to stack. We can evaluate the formula above to get
n = (√(72 + 1) - 1) / 2 = (√(73) - 1) / 2 = 3.772001873
Rounding up gives k = 4, so you'd need a stack of height 4.
Suppose you have 137 fruit to stack. The same formula gives back n = 16.060495162, so you'd need a stack of height 17 to store the fruit.
Hope this helps!
I was given the following code:
public int func(int n){
if(n == 1)
return 2;
else
return 3 * func(n-1)+1;
}
I can understand recursion in things like factorial and fibonacci, but for this one I cant.
I tried to trace the logic:
if n is 3:
return 3 * func(2) + 1
return 3 * func(1) + 1
return 3 * 2 + 1
return 7
I always end up with 7 with any other number and I know this is wrong because I get different values when I run the program. Can you help me understand how recursion works here?
I think this is self-explanatory, if you need more informations just comment !
if n is 3:
return 3 * func(2) + 1
return 3 * (3 * func(1) + 1) + 1 //func(2) is equals to 3 * func(1) + 1
return 3 * (3 * 2 + 1) + 1 //func(1) is equals to 2
return 22
If n is 1 it returns 2 (so func(1) = 2).
If n is 2 it returns 3 * func(1) + 1, which is 3 * 2 + 1 = 7 (so func(2) = 7).
If n is 3 it returns 3 * func(2) + 1, which is 3 * 7 + 1 = 22 (so func(3) = 22).
If n is 4 it returns 3 * func(3) + 1, which is 3 * 22 + 1 = 67 (so func(4) = 67).
...
And so on. In other words, when n = 1 it simply returns 2 and it all other cases it returns the value for func(n - 1) times three and with one added.
if n is 3
func(3)
=3*func(2)+1
=3*(3*func(1)+1)+1
=3*(3*2+1)+1
=22
if n is 4
func(4)
=3*func(3)+1
=3*22+1
=67
You're close, but missing a key point:
func(3) is: 3 * func(2) + 1
func(2) is: 3 * func(1) + 1
func(1) is: 2
Therefore, func(2) is 3*2+1 = 7.
And func(3) is 3*7+1 = 22
when n=3 you get
func(3) = > return 3 * func(2) + 1
where func(2) is
func(2) = > return 3 * func(1) + 1
where func(1) is
func(1) = > return 2
once you combine them you get that
func(3) => return 3 * (3 * (2) + 1) + 1
func(3) => return 22
You have to reinput that value you get for the deepest recursion call into the previous level and so forth.
func(1) = 2
func(2) = 3 * func(1) + 1 = 7
func(3) = 3 * func(2) + 1 = 22
func(4) = 3 * func(3) + 1 = 67
As a general rule a recursive method has two parts,
The part for solving primitive problem, here in your example is
if(n == 1)
return 2;
The part for dividing the problem into smaller problems so that finally it falls under part 1 (primitive problem)
else
return 3 * func(n-1)+1;
This is the very nature of Divide and Conquer algorithms that tend to divide the problem into smaller pieces in each round until they became solvable. Then by joining the solved pieces, the original problem gets solved.