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.
Related
I've been given a problem about finding all the possible combinations to change a 5 euro note. I've written a program that fails to result the correct number of combinations.
My approach was inspired from the following:
500 can be divided into 200, 200 and 100.
200 can be divided into 100 and 100.
100 can be divided into 50 and 50.
After I've written my code, I've realised that 100 can also be divided into 5 20's. This is a fault which I am aware of but I do not know how to fix using my approach.
My approach was a recursive one as can be seen below, it simply checks the first digit and divides it accordingly.
Here is what I tried:
public class Q1 {
public static int counter;
public static void main(String[] args) {
divide(500);
System.out.println(counter);
}
private static void divide(int x) {
System.out.println("Dividing " + x);
if(x == 1) {
return;
}
counter++;
int length = String.valueOf(x).length();
int fd = Integer.parseInt(Integer.toString(x).substring(0, 1));
String zeros;
if(fd != 1) {
zeros = Integer.toString(x).substring(1, length);
}else {
zeros = Integer.toString(x).substring(1, length-1);
}
if(fd == 5) {
divide(Integer.parseInt(2 + "" + zeros));
divide(Integer.parseInt(2 + "" + zeros));
divide(Integer.parseInt(1 + "" + zeros));
}else if(fd == 2) {
divide(Integer.parseInt(1 + "" + zeros));
divide(Integer.parseInt(1 + "" + zeros));
}else if(fd == 1) {
divide(Integer.parseInt(5 + "" + zeros));
divide(Integer.parseInt(5 + "" + zeros));
}
}
}
For example using the above program misses
10 = 2 + 2 + 2 + 2 + 2
I am aware of working solutions already present like this one but I would like to maintain my approach if possible.
Using the program to finding out the combinations for 500 cents results 388 ways, where the correct answer is 6295435. Something tells me I'm forgetting something else other than the above example.
Here are some hints about why you get the wrong number:
A correct way to determine all possibilities
Try to split 5 instead of 500 for simplicity. Notice that there are 4 possibilities, namely 5 =
5
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
Now try dividing 10 instead of 500.
Notice that this can be split up into 11 different ways:
10 =
10
5 + 5
5 + 2 + 2 + 1
5 + 2 + 1 + 1 + 1
5 + 1 + 1 + 1 + 1 + 1
2 + 2 + 2 + 2 + 2
2 + 2 + 2 + 2 + 1 + 1
2 + 2 + 2 + 1 + 1 + 1 + 1
2 + 2 + 1 + 1 + 1 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
This solution follows the following pattern:
The number x you want to split is already an answer.
Decrease the amount of lowest numbers by 1 by splitting one of these numbers into as many next largest numbers as possible. Always ignore ones. If there is only one number (and ones) left, split x into as many next lowest numbers as possible and continue.
For example, x = 10. Then: 10 is the lowest number -> split it up into 5 + 5 -> 5 is the lowest number ->split it up into 2 + 2 + 1 -> 2 is the lowest number since ones are ignored -> split it up into 1 + 1 -> we have another 2, split it up into 1 + 1 (this is equal to the solution 5 + 1 + 1 + 1 + 1 so now we have 5 as only one number apart from ones. Next lowest number is 2)-> split x=10 into 2 + 2 + 2 + 2 + 2 -> 2 is the lowest number; split it into 1 + 1 -> we have another 2 ...
This can be done in an recursive approach.
Things that went wrong in your code
What you code does with the example of dividing 10 is the following:
10 is divided into 5 + 5
the first 5 is divided into 2 + 2 + 1
one of these twos is divided into 1 + 1
the other two is divided into 1 + 1
Now, the second 5 from the division into 5 + 5 is divided into 2 + 2 + 1
One of these twos is divided into 1 + 1
The other two is divided into 1 + 1
Giving it a total score of 7 possibilities.
Trying to map These 7 possibilities to the 11 above, you count 10 =
10 once
5 + 5 once
5 + 2 + 2 + 1 twice
5 + 2 + 1 + 1 + 1 twice
5 + 1 + 1 + 1 + 1 + 1 twice
and missing the other 6 options.
So the assumption that this question can be solved by an approach like this one:
10 = 5 + 5 -> evaluate the first 5, then evaluate the second 5
is wrong because in both cases this leads to a distribution of 10 = 5 + evaluation of 5, counting only the options where at least one 5 is contained in the final distribution of 10 (counting it multiple times whearas distributions without fives are not evaluated).
Another mistake is that the code says there is no possible distribution of 1 where there actually exists one (1 = 1).
Also, the question is unclear about
can x equal all possible whole numbers? -> 4 is not split up into 2 + 2 in your Code
is 1 + 1 + 2 a different solution from 1 + 2 + 1 and 2 + 1 + 1?
(I don't have the reputation to ask this in a comment yet).
Remaining an recursive approach can only be done with some significant changes. A possible way to do so is stated above.
class Example {
public static void main(String args[]){
System.out.println(12+8/5%4*(5-4/5)+4*5);
}
}
Why the output is 37? Can anyone explain? I'm a beginner in java
Check the precedence of the operators in java:
12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0)+4*5
12+8/5%4*5+4*5
12+1%4*5+4*5
12+1*5+4*5
12+5+20
37
You have: 12+8/5%4*(5-4/5)+4*5
In the post of user3134614
12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0)
12+8/5%4*5+4*5
12+1%4*5+4*5
12+1*5+4*5
12+5+20
37
You have the basic operators
+ add two numbers
- subtract two numbers
* Multiply two numbers
/ divide two numbers
And these, a little more advanced
% gets the remainder of two numbers, that is, that divides them and obtains the remainder, if the number is even, then the rest is zero, and if it is odd, it is another number
For example 4%4 would be 4 divided by 4 results in 2 and 2 + 2 = 4, there is no remainder, on the other hand 5%4 = 1, because 2 + 2 = 4 and over 1 of 5
The parentheses () separate a mathematical expression and return it as a single quantity, example
5 - (3-2) * 2 is equivalent to 5 - (1) * 2 = 5 - 2 = 3
Then
12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0) is 12+8/5%4*(5 - (4/5) = 0.8, but converted to integer is 0, then 5 - 0 = 5)
12+8/5%4*5+4*5 is 12+ (8/5 = 1.6, but to integer is 1) %4*5+4*5
12+1%4*5+4*5 is 12+ (1%4 = 1 (1 is different of 4 then result is 1)) *5+4*5
12+1*5+4*5 is 12 + (1*5 = 5) + (4*5 = 20)
12+5+20 and 12 + 5 + 20 = 37
37
The wording of the problem is
"Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:"
The table is essentially:
1 = 1
2 = 1 1
3 = 2 1 2
4 = 2 1 1 2
5 = 3 2 1 2 3
6 = 3 2 1 1 2 3
My attempted code is
public void writeSequence(int n){
if (n < 1){
throw new IllegalArgumentException();
}
if (n == 1){
System.out.print(n + " ");
}
else if (n == 2){
System.out.print(1 + " " + 1 + " ");
}
else if (n % 2 == 0){
System.out.print(n - (n/2) + " ");
writeSequence(n - (n/2));
System.out.print(n - (n/2) + " ");
}
else{
System.out.print(n-(n/2) + " ");
writeSequence(n - 2 );
System.out.print(n-(n/2)+ " ");
}
}
For inputs 1-10, my code is not generating the correct answer for 6, 8, and 10. Any help is greatly appreciated.
Edit:
Fixed spelling in title
Edit 2:
My results are
1 = 1
2 = 1 1
3 = 2 1 2
4 = 2 1 1 2
5 = 3 2 1 2 3
6 = 3 2 1 2 3 (wrong)
7 = 4 3 2 1 2 3 4
8 = 4 2 1 1 2 4 (wrong)
9 = 5 4 3 2 1 2 3 4 5
10 = 5 3 2 1 2 3 5 (wrong)
If someone could show me where I have made an error in my code that would be great!
Your recursive call passes the incorrect value. Each time the algorithm recurses, it should decrease the value by 2.
Change this:
writeSequence(n - (n/2));
to this:
writeSequence(n - 2);
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
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!