Although I think I have a solid understanding of resolving stacks in void methods, return methods really mess up my understanding of stacks. The following method particularly confuses me as I would have thought that it would return 0, but returns 12 instead.
public static int mystery(int n) { // where the method call is mystery(7)
n--; // since n is decremented before the first
// recursive method, the first stack is method(6)
if(n > 0) // base case
mystery(n);
return n * 2; // 0 * 2 = 0?
}
My question is why does the method output 12 when mystery(7), if 0 is the last value to go into the stack. Wouldn't this method still follow LIFO?
This has to be like this:
public static int mystery(int n) { // where the method call is mystery(7)
n--; // since n is decremented before the first
// recursive method, the first stack is method(6)
if(n > 0) // base case
n = mystery(n);
return n * 2; // 0 * 2 = 0?
}
Now it will return 0 always.
From the inside out:
The innermost call to mystery (n is 1 on entry) returns 0 to its caller. The return value is not used.
The next level of mystery (n is 2 on entry) returns 2 to its caller. The return value is not used.
...and so on...
The next-to-outermost level of mystery (n is 6 on entry) returns 10 to its caller. The return value is not used.
The outermost level of mystery (n is 7 on entry) returns 12 to its caller, which is the final return value.
Let's not consider 7. Let's say your value is 3. mystery(3). In this case, the function will run 3 times.
First run:
n = 3;
n--; // n = 2
(n > 0) so mystery(2)
Second run:
n = 2;
n--; // n = 1
(n > 0) so mystery(1)
Third run:
n = 1;
n--; // n = 0
(n = 0) so return the n*2 . And the return will be 4
Why? Cause the recursive function does not change the value of n
Related
I am new to Java and am I trying to implement a recursive method for finding "n choose k".
However, I've run into a problem.
public class App {
public static void main(String[] args) throws Exception {
int n = 3;
int k = 2;
int result = combRecursion(n, k);
System.out.println(result);
}
private static int combRecursion(int n, int k) {
if (k == 0) {
return 1;
} else {
return (combRecursion(n - 1, k - 1) + combRecursion(n - 1, k));
}
}
Output:
many repetitions of this line:
at App.combRecursion(App.java:14)
It's possible to pick k items from the set of n items only if n is greater or equal to k.
You need to cut off fruitless branches of recursion spawn by the call combRecursion(n - 1, k) which doesn't reduce the number of item in the sample.
When you need to create a recursive method, it should always contain two parts:
Base case - that represents a set of edge-cases, trivial scenarios for which the result is known in advance. If the recursive method hits the base case (parameters passed to the method match one of the conditions of the base case), recursion terminates. In for this task, the base case will represent a situation when the source list was discovered completely and position is equal to its size (invalid index).
Recursive case - a part of a solution where recursive calls are made and where the main logic resides.
Your recursive case is correct: it spawns two recursive branches of execution (one will "pick" the current item, the second will "reject" it).
But in the base case, you've missed the scenario mentioned above, we need to address these situations:
n isn't large enough (k > n), so that is not possible to fetch k item. And the return value will be 0 (or instead of returning a value, you might throw an exception).
k == 0 result should be 1 (it's always possible to take 0 items, and there's only one way to do it - don't pick anything).
When k == n - there's only one way to construct a combination, as #akuzminykh has pointed out. And the return value will be 1
Note that because your goal is to get familiar with the recursion (I'm pretty sure that you're doing it as an exercise) there's no need to mimic the mathematical formula in your solution, use pure logic.
Here is how you can implement it:
private static int combRecursion(int n, int k) {
if (k > n) return 0; // base case - impossible to construct a combination
if (n == k || k == 0) return 1; // base case - a combination was found
// recursive case
return combRecursion(n - 1, k - 1) + combRecursion(n - 1, k);
}
main() - demo
public static void main(String[] args) {
System.out.println(combRecursion(3, 2));
System.out.println(combRecursion(5, 2));
}
Output
3 // pick 2 item from the set of 3 items
10 // pick 2 item from the set of 5 items
Your base case ought to include both n == k || k == 0 for "n choose k" to be implemented correctly. That way, both calls will eventually terminate (even though your current implementation is rather inefficient as it has exponential runtime). A better implementation would use the formula n!/k!/(n-k)! or the multiplicative formula to run in linear time:
int factorial(int n) {
int res = 1;
for (; n > 1; n--) {
res *= n;
}
return res
}
int choose(int n, int k) {
return factorial(n)/factorial(k)/factorial(n-k);
}
further optimizing this is left as an exercise to the reader (hint: a single for loop suffices).
Basically what I have to do is to remove all digits and leave the first one. If it's a number under 10 keep that number.
I already made some code but instead of removing all digits following the first, I removed the first digit.
My code:
public static int keepFirstDigit(int num) {
// Can't change anything besides the following code
if(num==0){
return 0;
}
if(num>0){
return num % (int) Math.pow(10, (int) Math.log10(num));
}
return num;
}
If the number is 5, the output should be 5.
If the number is 23 the output should be 2.
If the number is 62363456 the output should be 6.
First, you need to understand what is recursion and how it works.
Recursion means function/method call itself.
in below program removeDigit method calling itself if n is greater than 10 with n = n/10.
try this one.
public class Main {
public static void main(String[] args) {
System.out.println(removeDigit(23219));
}
public static int removeDigit(int n) {
if (Math.abs(n) < 10) {
return n;
}
return removeDigit(n/10);
}
}
for n = 23219
iteration 1
23219 > 10
call removeDigit with n = 23219/10 = 2321
iteration 2
2321 > 10
call removeDigit with n = 2321/10 = 232
iteration 3
232 > 10
call removeDigit with n = 232/10 = 23
iteration 4
23 > 10
call removeDigit with n = 23/10 = 2
iteration 5
2 < 10
So return 2
I am not sure if recursion is the best tool to do it however this should work :
public static int keepFirstDigit(int num) {
//Can't change anything besides the following code
if(num < 10) {
return num;
} else {
return keepFirstDigit(num / 10);
}
}
If num is less then 10 we jest return it. Otherwise we divide num by 10 without the remainder and pass it to recursive method call.
For negative numbers we could change the negative number to positive as this does not affect first digit :
public static int keepFirstDigit(int num) {
num = Math.abs(num);
if(num < 10) {
return num;
} else {
return keepFirstDigit(num / 10);
}
}
We could also do the abs before calling this method and pass it as parameter.
I'm not sure if you need to do it recursiveley but if you don't, I'd do it like this
public static int keepFirstDigit(int num) {
String tempNum = String.valueOf(num).substring(0,1);
return((int) Integer.parseInt(tempNum));
}
but if you do, just use the other examples that have already been posted
This can also be achieved using Strings, maybe think of this:
public static int keepFirstDigit(int num) {
//Can't change anything besides the following code
return Integer.parseInt((num+"").charAt(0)+"");
}
Based on #Pankaj Singh and #michalk answer, here is a working, verifiable solution in Javascript.
It also handle negative and null values.
Run it to see output and results.
(Probably not the fastest, shortest way though)
Result for 0 -> 0
Result for 10 -> 1
Result for -10 -> -1
Result for 9.9999 -> 9
Result for 1.57 -> 1
Result for 23 -> 2
Result for 34.5 -> 3
Result for 5678848 -> 5
Result for -3.14159 -> -3
Result for -28.123 -> -2
// Define a function doing the job
// Take an object as argument, not a number (for updating purpose)
const getFirstDigit = (obj) => {
// Ensure argument is valid
if (!obj || !obj.count) {
return;
}
if ((obj.count >= 0 && obj.count < 10)
/* handle negatives */
|| (obj.count <= 0 && obj.count > -10)) {
// Ensure it is an integer
obj.count = parseInt(obj.count);
} else {
// Divide by ten: update obj.count
obj.count = parseInt(obj.count / 10);
// Recursion: call again since number is greater or equals than 10
getFirstDigit(obj);
}
}
// At the end of recursion stack, obj.count will be an integer < 10 == the first digit of initial number
// Give some inputs (and negative values)
let numbers = [0, 10, -10, 9.9999, 1.57, 23, 34.50, 5678848, -3.14159, -28.123];
for (index in numbers) {
let input = numbers[index];
// Prepare an object to hold our number
let object = { count: input };
// Call the method by passing an object
// Passing an object rather a primitive Number allow the function to update the object by reference
getFirstDigit(object)
// Retrieve object updated (or not) number
let output = object.count;
console.log(`Result for ${input} -> ${output}`);
}
This is the code for a function that is supposed to return true if the input is prime and returns false if it is not.
This is how I intended for it to work: lets say that y = 7, the loop starts with n=1. Since 1(n) is less that 7(y) the loop can iterate. The program checks if y divided by n has a remainder of 0, meaning that n is a factor of y. If it is true, then it checks to see if the factor does not equal 1 or y (7), because if they dont then that means that y has more factors other than its self and 1, meaning that it is not prime, so it should automatically end the function and return false. but since 7 has only two factors, 1 and 7, and they either equal 1 or itself (y) then after the end of the loop, it should return true.
I don't understand why it isn't working.
public static boolean checkIfPrime(long y) {
for ( long n =1L; n <= y; n++) {
if(y%n == 0) {
if( n != 1L || n != y) {
return false;
}
}
}
return true;
}
With a few optimizations the code will be like this
static boolean isPrime(long n){
long lim = (long) Math.sqrt(n);
if(n%2 == 0 && n != 2)
return false;
for (int i = 3; i <= lim; i=i+2)
if(n%i == 0)
return false;
return true;
}
This code:
checks if the number is even and different from 2 (all even numbers
except 2 are compound).
next iterates from 3 to sqrt(n), thats because to prove a number is
prime you don't need to check all the dividers (if you don't believe
me try, and if still don't believe use n/2 wich is enough but not the
minimum value).
For loop pace start from 3 and add 2 in each iteration getting only odd numbers as divder (we first checked that it wasn't an even number).
Remove equal to operator in n <= y. Start your loop from 2. It must be like this. ( long n =2; n < y; n++)
For what you are trying to achieve, pseudo code in my opinion should look like this:
set a flag = true;
Loop from 2 to y-1{
if(y%n==0){
flag = false
break; // Very important
}
}
check flag condition & return (if some othe computation is required) or just return flag
if( n != 1L || n != y) : is adding a check condition unnecessarily to every iteration. try to avoid it.
Why use a flag instead of direct return statement ? Just a preference, a direct return definitely would work in this case.
I'm new to Java and I'm reading a couple of books about it.
I can't figure out how the output of this code produced:
import java.util.*;
class myclass {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println(factorial(myScanner.nextInt())+"\n");
}
public static int factorial(int n) {
if (n==0) {
return 1;
} else {
int recurse = factorial(n-1);
int result = recurse*n;
return result;
}
}
}
Can anyone please explain this step-by-step for me?
I understand the main method and Scanner class, but I don't understand that when I enter an integer like 8 at input, I get 40320 at output.
Code is easier to work through when you format it properly, so please do that in the future. Sometimes code is also easier to work through when you make it more concise. Notice that you can "inline" the result variable:
public static int factorial(int n) {
if (n == 0) {
return 1;
}
else {
int recurse = factorial(n - 1);
return recurse * n;
}
}
Or more simply:
public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n-1);
}
Now let's try some values. Let's try with the value of "0":
public static int factorial(int n) {
if (n == 0) {
return 1; //<-- Returns 1
}
return n * factorial(n-1);
}
Ok, that's right: 0! = 1.
Let's try with the value of "1":
public static int factorial(int n) {
if (n == 0) {
return 1; //not reached
}
return n * factorial(n-1); //<-- 1 * factorial(0) = 1 * 1 = 1
}
Good: 1! = 1.
Let's try with the value of "8":
public static int factorial(int n) {
if (n == 0) {
return 1; //not reached
}
return n * factorial(n-1); //<-- 8 * factorial(8-1) = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 40320
}
This makes sense since 8! = 40,320.
The way this is done is called recursion since the method is essentially calling itself. When done well, recursion is a beautiful part of programming since the code is typically fairly concise and is one of a "divide and conquer" mentality. This is an introductory concept in programming.
A good programmer will always be thinking about the system of values. So in this case, your function will provide a StackOverFlow error if n is -1, for example. (You can change the code to read if (n <= 1)).
The function factorial uses recursion to solve the factorial. This means that the function calls itself multiple times, until n becomes 0 (In which it returns 1).
So for n = 3, the program starts by setting the result to
Factorial(3) = factorial(2) * 3,
Factorial(2) = factorial(1) * 2,
Factorial(1) = factorial(0) * 1,
Factorial(0) = 1 (Because of the *if-statement*)
Now you can add the things together, as it knows what Factorial(0), Factorial(1), Factorial(2) and Factorial(3) is.
It then becomes:
Factorial(0) = 1,
Factorial(1) = 1 * 1 = 1,
Factorial(2) = 1 * 2 = 2,
Factorial(3) = 2 * 3 = 6
First of all: Factorial function
I suppose that you don't understand the recursive factorial function.
Declaration of the function:
public static int factorial(int n){
The factorial of 0 is 1 (the exception):
if(n==0){
return 1;
}
If the number introduced by the user isn't 0 then:
else {
int recurse = factorial(n-1);
int result = recurse*n;
return result;
}
In this case, for example, call the function with 2. recurse = factorial(2-1), wait until the call to the function ends (in this case calls to the same function, but it isn't a problem, just wait until the function call ends). Therefore call factorial(2-1). To be continued...
factorial(1), n==0 false, therefore get inside else statement. Call factorial(1-1). Another time wait until the function factorial(1-1) ends. To be continued...
factorial(0), n==0true, therefore return 1. The call to the functions ended, now we will continue the step 2.
Continue factorial(1) in step 2: The factorial(1-1) returns 1 and store it in recurse.int result = recurse * n so result = 1·1. Finally in this step return result (1). Now we go to step 1 that is still waiting in the factorial(1) call.
Continues factorial(2) in step 1: The factorial(2-1) returns 1 ans store it in recurse. int result = recurse * n so result = 1·2. And return result (2).
Finally the factorial(2) returns 2. Think about factorial(3), 4, 5, 6, 7, and finally you will understand factorial 8. The most important thing is that, when you call the same function where you are, it save the state in a stack and wait until it finish.
Would anyone be able to explain these methods with a few comments line. They are for squaring a number. One is using recursion, implementation and another is just normal
public static int sq(int n)
{
int i = 0 ;
int result = 0 ;
while(i < n){
result = result + 2*i + 1 ;
i = i + 1 ;
}
return result ;
}
public static int recSq(int n)
{
if(n == 0){
return 0 ;
} else {
return recSq(n - 1) + 2*(n - 1) + 1 ;
}
}
public static int implementSq(int n)
{
int i ;
int result = 0 ;
for(i = 0 ; i < n ; i++){
result = result + 2*i + 1 ;
}
return result ;
}
I presume this must be a homework exercise, otherwise its an insane way to do anything. Therefore can I suggest using an integrated development environment (e. g. Netbeans) and then using it to step through the code line by line. This is by far the easiest way to understand what the code is doing. If we just tell you, you won't gain anything by it.
The first one is multiplying the number by 2 n times using a loop to increase a local variable i.
The second one is doing exactly the same but using recursion. Each step decreasing n and returning 0 for the final case. All the calls are calling again to the same function with different parameters exept for the parameter value 0, then the function will return 0. Recursion is not a simple thing to think off, to understand it better try to imagine the codeflow.
Example: recSq(2)
4 recSq(2)
|<- 1 reqSq(1)+2*1+1
|<-0 reqSq(0)+2*0 + 1
|<- 0
reqSq(2) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 2 then we call to reqSq(1).
reqSq(1) is called so we will eval the if and start evaluating the return statement. The first operation is a method call to reqSq(n-1) as n = 1 then we call to reqSq(0).
reqSq(0) is called so we will eval the if, it's true cause n ==0 and then we return 0.
reqSq(1) call has finished evaluating reqSq(0) and then we can proceed calculating the rest 0 + 2*(n-1) + 1 -> 0 + 0 + 1. We will return the value 1.
reqSq(2) has finished evaluating reqSq(1) and then we can proceed calculating the rest 1 + 2*(n-1) +1 -> 1 + 2 + 1. We will return the value 4.
The last one is a for loop, practically the same as the first one but using fors instead of while loops. In a for loop you declare in one line the initialization condition, the continue condition and the increase operation. So in that case the for loop is starting with value 0, the loop will continue as i < n and at the end of the loop "i++" will be called.
why are you trying to solve such a simple problem with recursion or loop?
public static int sq(int n) {
return n * n;
}
that's it.