I been trying to figure out how to solve this question but I do not understand. If i take mystery(2,25), b is not ==0 and b%2=1 so then I have mystery(2+2, 25/2) + 2. I dont understand what I do with the +2 in the end and I dont understand if I am supposed to add a and b or to do the code again with the new values.
What are the values for mystery(2, 25) and mystery(3, 11) respectively?
public static int mystery(int a, int b) {
if (b == 0) return 0;
if (b % 2 == 0) return mystery(a+a, b/2);
return mystery(a+a, b/2) + a;
}
Answer to choose from:
33554432, 177147
525, 1331
50, 33
75, 44
I create an image trying to illustrate the answer...
-About the +2 you have to add after the return of the next call back...
Note: If you pass a float value to int parameter as 12.5 the parameter will get only the integer part: 12
If it is ok, please check as correctly! ;)
Evaluate each call to mystery until b is 0 and the recursive call chain terminates. You then add the final 0 result with the intermediate a (the +a) in the code.
Related
I'm fairly new to programming and I started to write some basic codes. I tried to create an algorithm that found every position of the character you wanted in a string. If I were to enter "helllo" as a string and wanted to search for the character l, it would output 2, 3 and 4. The code worked fine until I tried to trick the code a bit to change something. To do so, I first removed the termination condition in the "for loop" and instead added an if statement during the loop to break it. I spent about 2h on the error that occurred after and I still can't find out what's happening.
Here's the code and the output it gives me. (I know my code is a mess and not properly optimized, but right now I would just like to know what is happening. I'll rearrange it later if I get it to work. thank you^-^.)
When I run the code, instead of displaying as it should, "7, 8, 9, 10"(it searches for the character ^ in the string Oioriew^^^^) it outputs "7-1,8,9,10". To fix it, I can simply insert the termination condition in the loop again, which was, "pow != -1" but at this point, I really want to know why it happens.
public class Tests {
static void zeMethod(String mainString,char charToFind) {
int a = 0;
String b, c;
char chartToConvert;
c = "";
b = "";
for (int pow = mainString.indexOf(charToFind);
; // *the condition was here.*
pow = mainString.indexOf(charToFind, pow + 1)) {
a++;
if (a == 1){
System.out.println("String: "+mainString);
System.out.println("il y a un "+charToFind+" à la/aux position(s)");
}
if (a == 1){
System.out.print(pow);
}
if (a%2 == 0 && pow != -1) {
c = b+", "+pow;
}
if (a%2 != 0 && a != 1 && pow != -1) {
b = c+", "+pow;
}
if (pow == -1){
System.out.print(pow);
break;
}
//*end of loop*
}
if (a%2 != 0){
System.out.println(c);
}
else {
System.out.println(b);
}
}
public static void main(String[] args){
String string = "Oioriew^^^^";
char chara = '^';
zeMethod(string, chara);
}
}
I'm sorry if my question is a bit incoherent or not properly asked. This is my first time on the site and English isn't my mother language. Thank you for your time!
Edit:
I know the question wasn't clear at first, but what I meant is, why does pow become -1 after the second iteration of the loop. Also, why does the break after the System.out.print(pow); doesn't make it leave the loop. (I'm looking how to make a debugger work atm too.)
[...] instead of displaying as it should, "7, 8, 9, 10" [...] it outputs "7-1,8,9,10 [...] I really want to know why it happens
Sounds like you're asking why it prints -1, which happens because you explicitly asked it to:
if (pow == -1){
System.out.print(pow);
break;
}
If pow is -1 then print pow (aka -1) and exit the loop.
UPDATE
As for why the order of the output, use a debugger and step through the code one statement at a time, and you'll see.
But, lets see: We can agree that loop will iterate with pow having these numbers in this order: 7, 8, 9, 10, -1
Why does it print 7 first?
Because you have this code inside the loop:
a++;
if (a == 1){
System.out.print(pow);
}
Why does it print -1 next?
Because there are no other print statements inside the loop, which would be a lot more apparent if you indented the code correctly, i.e. indented the content of the loop.
Why does it print 8,9,10 last?
Because you print the content of b or c after the loop, and that is the content of whichever one of them is being printed.
Note that first value (-7) is not added to b, because you explicitly exclude it in the if statement.
I'm all good, thank you all for your time and Andreas, for the debugger option. It's a must-have for anyone programming. I don't know how I didn't see this earlier, but to break, it had to become -1 and since I had to break before I could print my answer, -1 was first.
I think I've gotten mostly to a solution for a homework problem.
This is for a 201 CS class. Right now I just want to get the logic right. At present, it doesn't operate as intended, but it's close.
We don't want to use .toBinary, bitwise, or anything else. We also haven't been taught stringBuilder, so I'd like to avoid using it.
There's a System.out.println(); within the method which provides the correct answer if you read the console from bottom to top.
public static void main(String[] args) {
System.out.println(addBin(1100111011,1101110011));
}
public static String addBin(int num1,int num2){
String result = "";
if(num1 > 0 || num2 > 0){
int part1 = num1%10, part2 = num2%10;
int rem1 = num1/10, rem2 = num2/10;
result += Integer.toString((part1 + part2)%2);
//System.out.println(result);
int carry = (part1 + part2) /2;
addBin(rem1 + carry, rem2);
return result;
}
return result;
}
So, this example adds 1100111011 and 1101110011 with the output
0
1
1
1
0
1
0
1
0
1
1
0
when the correct answer is 11010101110.
I'm having trouble understanding how to properly "pop" the "result" part properly. Could you please help me understand this process, possibly within the context of this problem?
Thanks!
As you can see from your output, you are getting the correct result in the reverse order but you are not appending any of your older result to the ones that are being currently computed.
Inside your if condition, you are calling the addBin() function but you are not using the result that it gives anywhere. Just change that line to the following:
result = addBin(rem1 + carry, rem2)+result;
That should effective append all your results in front of the current answer so that you do not get the result in backwards direction. Hope this helps.
I have been given this on a mock programming exam and I am not too good with this type of thing, can someone explain to me how I would go through something like the following? change the values to the one in the question if you feel like it explains it better. It is the final else which is really throwing me off. Thank you for the help.
public int function( int a, int b)
{
if (a<=0){
return b;
}
else if (b<=0)
{
return function( a-2, 0);
}
else
{
return function (function (a-1, b-1), b-1);
}
I interpret your (1,1) as a = 1 and b = 1. That said:
a = 1 > 0, the enter condition is false, so the first branch is not taken:
if (a<=0)
We go on until the second branch. b = 1 > 0 the enter condition is false again, so we won't take this branch neither:
else if (b<=0)
eventually, we reach the else branch and we take it:
else
So we land in this line:
return function (function (a-1, b-1), b-1);
There is a recursion, here! First call is function (a-1, b-1), so we are calling function with a = 1 - 1 = 0 and b = 1 - 1 = 0. Let's start again as above:
a = 0, so we take the first branch:
if (a <= 0)
and we return b = 0.
Now, it's time for the second recursion. We have a = function(a - 1, b - 1) = 0 and b = 1 - 1 = 0. It's still a = 0 and b = 0, so the result will be 0 as above.
Finally, we return 0.
Alright, I will step through other values so you can learn how to do it yourself.
lets take the values 2,2 for example.
check the first if statement(if (a<=0)) to see if its valid
a=2 so replace a with the value 2
is 2 <= 0? Nope. Lets go to the next statement
else if (b<=0)
NOTE: else if is essentially a statement that it used if the previous if statement for fails.
b = 2 is 2<=0? Nope. ONTO THE NEXT ONE!
else handles everything that fails under the first if and all the proceeding else ifs
So just plug in the values.
a = 2 b = 2
return function (function (a-1, b-1), b-1);
-->
return function (function (2-1, 2-1), 2-1);
-> return function (function (1, 1), 1);
You can go two ways with this keep recurring down or logically think about it.
Now... lets start noticing a pattern here and look for a base case (usually used for recursive functions like these) so you notice return b on the first if statement will ALWAYS be the actual returning result in the end and all the other recurring will stem off that result, because that's the only real value you will return. Now we got that established
How can we get to that value? if statement a<=0 is the only way to get there. You start noticing the relationships.
input a <= b or a <= 0 output b
input a > 0 a > b output 0
I can't seem to figure this one out. I need to count how many numbers below a given number in which it is divisible.
Here is what I've tried:
public int testing(int x) {
if (x == 0) {
System.out.println("zero");
return x;
}
else if ((x % (x-1)) == 0) {
System.out.println("does this work?");
x--;
}
return testing(x-1);
}
That doesn't work and I don't know where to go from here. Anyone know what to do?
This is what is wrong:
public int testing(int x) {
If you want to make it recursive, you need to pass both the number to test and the number that you are currently checking. The first one will not change through the recursion, the second one will decrement. You cannot do what you express with only one parameter (unless you use a global variable).
This is not a task that should be solved with recursion.
If you MUST use recursion, the simplest way to do it is to have a second parameter, which is essentially an "I have checked until this number". Then you can increase/decrease this (depending on if you start at 0 or the initial number) and call the recursive on that.
Thing is, Java isn't a functional language, so doing all this is actually kind of dumb, so whoever gave you this exercise probably needs a bop on the head.
Your problem is that your expression x % (x - 1) is using the "current" value of x, which decrements on every call to the recursive function. Your condition will be false all the way down to 2 % (2 - 1).
Using a for loop is a much better way to handle this task (and look at the Sieve of Eratosthenes), but if you really have to use recursion (for homework), you'll need to pass in the original value being factored as well as the current value being tried.
You have a problem with your algorithm. Notice the recursion only ends when x == 0, meaning that your function will always return 0 (if it returns at all).
In addition, your algorithm doesn't seem to make any sense. You are basically trying to find all factors of a number, but there's only one parameter, x.
Try to make meaningful names for your variables and the logic will be easier to read/follow.
public int countFactors(int number, int factorToTest, int numFactors)
{
if (factorToTest == 0) // now you are done
return numFactors;
else
// check if factorToTest is a factor of number
// adjust the values appropriately and recurse
}
There is no need to use recursion here. Here's a non-recursive solution:
public int testing(int n) {
int count = 0;
for (int i = 1; i < n; i++)
if (n % i == 0)
count++;
return count;
}
BTW, you should probably call this something other than testing.
Using recursion:
private static int getFactorCount(int num) {
return getFactorCount(num, num - 1);
}
private static int getFactorCount(int num, int factor) {
return factor == 0 ? 0 : (num % factor == 0 ? 1 : 0)
+ getFactorCount(num, factor - 1);
}
public static void main(String[] args) {
System.out.println(getFactorCount(20)); // gives 5
System.out.println(getFactorCount(30)); // gives 7
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Horner's recursive algorithm for fractional part - Java
I am writing a program for Horne'r Algorithm, and I will be honest, I do not have much experience with recursion. I have this method set up to accept a fraction only (there is another method which accepts and returns the whole number) and it will return the result converted from base 'r' to base 10. I am unsure why, but the method does not seem to be going through the final iteration. Any suggestions as to what I need to do to correct this problem would be greatly appreciated.
(ex: c = 011, xFinal = 2, i = 2)
Expected answer = .375
Actual answer returned = .75
public static double getHornerFraction(long[] c, int xFinal, int i) {
if (i == 0) {
return ((double)c[i])/xFinal;
}
return (getHornerFraction(c, xFinal, i-1) + c[i])/xFinal;
}
From looking at what you specified and what you expect, I think the problem is that you are walking the array c in the wrong direction or otherwise specifying it incorrectly. I think that what you want to do is actually walk the array from index 0 to c.length.
public static double getHornerFraction(long[] c, int xFinal, int i) {
if (i == c.length) {
return 0;
}
return (getHornerFraction(c, xFinal, i+1) + c[i])/xFinal;
}
Call the above function with c = {0,1,1}, xFinal = 2, i = 0 and it should give what you expect.