public class Prod{
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
I've read a solution here: JAVA Recursive Program logic that makes some sense but I don't get why when it hits prod(1,1) it goes back to prod(1,2)
It will return the factorial of n with min limit m. Like
n * (n-1) * (n-2) * (n-3) * (n-4) * (n-5) ... till (n-x) != m
Sure. Let's add logging with some formatted output and I'd suggest you use a Conditional Operator ? : like
public static int prod(int m, int n) {
int recurse = (n != m) ? prod(m, n - 1) : 1;
int r = n * recurse;
System.out.printf("m=%d, n=%d, recurse = %d, returning %d%n", m, n,
recurse, r);
return r;
}
Output should explain your result
m=1, n=1, returning 1
m=1, n=2, recurse = 1, returning 2
m=1, n=3, recurse = 2, returning 6
m=1, n=4, recurse = 6, returning 24
24
Because it has prod(1,2) and other methods in the stack. Each time prod(m,n) is called it recursively calls prod(m,n-1) . This continues till m==n , in your case prod(1,1). Here prod(1,1) will return value to the calling method prod(1,2)
//method prod(1,2)
....
int recurse = prod(m, n-1);//here it will get value 1 returned from prod(1,1)
int result = n * recurse; // 2*1
return result; // return 2 to calling method prod(1,3)
So when finally recursive call ends at prod(1,1) and returns values. all the previous prod() present in the call stack will be execute each one getting return from called prod(m,n-1)
Related
I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower
I have a question how to better tackle this task, I have a version, but I am sure there is a better and shorter way to do this maybe. I need to take any int number(return it as an int without turning it into a String), but never with a 0 at the end (100, 120) but like 1234, or 4132. I need to take this number and using recursion rewrite it the other way around example 1234 to 4321, 4132 to 2314, maybe there is a way this is called, i personally don't know about it.
Here is what I got:
public static int reverse(int r, int n, int k){
if(r==0)
return 0;
else
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1)
}
public static void main(String[] args) {
System.out.println(reverse(1234, 4, 0));
}
Working with a String representation of the int may make the code more readable.
Try:
Integer.parseInt(new StringBuilder(r+"").reverse().toString());
Current code doesn't compile. Added a ) to this line:
from if(r==0{ change to if(r==0){
and added a ; in this line return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
Your code after this two changes will look like:
public static int reverse(int r, int n, int k){
if(r==0)
{
return 0;
}else{
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
}
}
if the number ends with 0, the program will not show any special message to the user, i.e 1230 will return 321. In this case, maybe
maybe print a message ("number must not end with a 0) or throw an exception?
Didn't notice the recursion part.
public static void main(String[] args) {
int i = 589;
System.out.println(reverse(i));
}
public static int reverse(int k){
if(k/10 == 0){return k;}
else return (k%10 * (int)Math.pow(10, (int)Math.log10(k))) + reverse(k /10);
}
Explanation:
k%10 gives you the last digit of an int
(int) (Math.log10(k)) returns
number of Digits in an Integer minus one
public static final int reverse(int number) {
final int lastDigit = number % 10;
final int length = (int) Math.log10(number);
return (number < 10) ? number : (int) (Math.pow(10.0, length) * lastDigit + reverse(number / 10));
}
If the number is lower then 10 it's the number itself. Otherwise it's the last digit multiplied with 10^n where n is the length of the number, so it's now at the position for the first digit.
Then add the result of a reverse of the rest number to it (the number without the last digit).
You take advance of the recursion function itself as it would already work to solve the big problem. You only have to think about the trivial end condition and one single step (which mostly is something you would suggest as the last step)
This is the best way that I could make it using recursion and without conversions.
private static int myReverse(int n, int r) {
if(n == 0)
return r;
int newR = r*10 + n%10;
return myReverse(n/10, newR);
}
What I'm doing here is:
Two parameters: n - the number you want to reverse, r - the reversed number
The recursion stops when n equals 0 because it always dividing it by 10
newR - This variable is unnecessary but it´s better for 'understanding' porposes, first I multiply r by 10 so I can sum the last value o n. For example, reverse 123: along the way if r = 12 and n = 3, first 12*10 = 120, n%10 = 3 then r*10 + n%10 = 123
A 'pleasant' way with only one return statement:
private static int myReverse2(int n, int r) {
return n == 0 ? r : myReverse2(n/10, r*10 + n%10);
}
java version "1.8.0_92"
I have the following code I am trying to understand and trace.
The part I don't understand is the * a at the end. When does that multiplication get called? And what is the return value of power1(a, n - 1);
Is it n - 1 * a
public static double power1(double a, int n) {
double result;
if(n == 0) {
return 1;
}
else {
result = power1(a, n - 1) * a;
return result;
}
}
You can modify the code to print a trace of the recursion. That can help you understand what is going on.
/**
* Print string form of `o`, but indented with n spaces
*/
private static void printIndented(int n, Object o) {
while (n-->0) System.out.print(" ");
System.out.println(o);
}
/*
* Added a third param `d` to keep track of the depth of the recursion
*/
public static double power1(double a, int n, int d) {
// Entering a "possible" recursive call
printIndented(d, "call power1, a=" + a + ", n=" + n + ", d=" + d);
double result;
if(n == 0) {
// Returning from the base case, this should have the largest depth.
printIndented(d, "return 1.0");
return 1;
}
else {
result = power1(a, n - 1, d + 1);
// Return from intermediate recursive calls, we print
// the value of power1(a, n-1) as well.
printIndented(d, "return " + result + " * " + a);
return result * a;
}
}
public static void main(String [] args) {
System.out.println(power1(1.4, 3, 0));
}
Output
call power1, a=1.4, n=3, d=0
call power1, a=1.4, n=2, d=1
call power1, a=1.4, n=1, d=2
call power1, a=1.4, n=0, d=3
return 1.0
return 1.0 * 1.4
return 1.4 * 1.4
return 1.9599999999999997 * 1.4
2.7439999999999993
As you can see, the value from the inner return becomes the result in the outer return statement.
Return value of power1(a,n-1)
We can see that power1 is defined as public static _double_ power1(double a, int n) This means that on the line
result = power1(a, n - 1) * a;
the type will be :
double = double * double;
When the multiplication gets called
We start our function with n and a. a will be constant in this implementation. It's given straight as to the next recursive call.
Yet n varies.
We call power1(a,n). It checks first if n == 0; It is not.
So we go to the else part of the if. Time to calculate result.
To know what the value of result is, we need power1(a,n-1). We proceed. n-1 can be 0 or can not be.
If it's 0, we return 1, and we now know that power1(a,n-1) = 1. We can now multiply it with a.
If it's not 0, then we need a new result, seeing as we're in a completely seperate call of the power1 method. We now need power1(a,n-2). We check again for 0. If n-2 == 0, return 1 to get the caller to calculate power(a,n-1). If not go down another call, now with n-3... Etc
In terms of the timing of calling the multiplication.
It's gonna call all the (n) recursive calls first, before doing n multiplications.
If you call power1 with a = 2 and n = 3, this is what will happen:
result = power1(2, 2) * 2;
power1(2, 2) = power1(2, 1) * 2;
power1(2, 1) = power1(2, 0) * 2;
power1(2, 0) = 1
In the above example, the * a happens three times in total. It is called whenever power1(a, n) returns a value. The first power1(a, n) to return a value will be power1(2, 0) (this is because n = 0 is your "base" case). Then power1(2, 1) will return 2. Then power1(2, 2) will return 4. Then your initial call to power1(2, 3) will return 8.
First you call power (a,n-1) until n == 0 which is your base case .
Then the 1 gets returned and is multiplied by the value of a.
Then a is returned to the previous call where it is multiplied by a . The process is repeated N times and thus you get A^n. I would recommend you go throught one example of this code giving it some initials values and tracing the code using pen and paper.
public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
On running the above code , I get 24 ?
I don't quite understand how?
My doubts:
1. When m =1 , n=4 , we call prod until m and n become equal to 1.
Then the output should be n and else block should not be executed??
Someone please help me understand the logic.
Just run through this with the numbers, you need to write it down to see the behavior exactly (in the future, I suggest adding lots of prints to your code to check variables and how they change with each pass through).
prod(1,4)
m=1,n=4
m != n so, recurse = prod(1, 3)
prod(1, 3)
m=1,n=3
m != n so, recurse = prod(1, 2)
prod(1, 2)
m=1,n=2
m != n so, recurse = prod(1, 1)
prod(1, 1)
m=1,n=1
m == n so,
return 1
returns to prod(1, 2)
recurse = 1
result = 2 * 1
return 2
returns to prod(1, 3)
recurse = 2
result = 3 * 2
return 6
returns to prod(1, 4)
recurse = 6
result = 4 * 6
return 24
Thus, your program prints 24.
Sometimes the best way to figure out a program is to mechanically go through the steps line by line, executing them in your head (or on paper to track things).
To understand any program with functions, you assume the called functions do their job right, and check that the calling function calls them in the correct order with the correct arguments, and combines the results correctly.
For recursive functions you need to check that each recursive call gets you closer to the case in which there is no recursion.
Here nobody told us what is the result supposed to be. The recursion ends whenever m == n, and the recursive call is with n = n - 1, so this will work only if m <= n.
Consider a string of calls, each one reduces n by 1, while m stays fixed. Say n == m + 3 for finding out what happens: The first call gets m + 2, the second m + 1, the third m, and returns m. The second takes n == m + 1 by m returned by the third, the second takes n == m + 2 and multiplies by the previous result, and finally the result is (m + 3) * (m + 2) * (m + 1) * m. This function computes n! / (m - 1)!, if n >= m. Knowing that this is what is going on, it is easy to check that our (up to now just) hunch is right.
prod(1, 4);
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
can be transformed with m == 1 to:
prodA(4);
public static int prodA(int n) {
if (1 == n) {
return n;
} else {
int recurse = prodA(n-1);
int result = n * recurse;
return result;
}
}
which has a transformation (head recursion):
public static int prodA(int n) {
int result = 1;
while (n > 1) { // Actually n != 1
result *= n;
--n;
}
return result;
}
which is the factorial function.
public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
Right now the method above does n * n into infinity if I debug it, so it still works but I need this recursive method to stop after 10 times because my instructor requires us to find the exponent given a power of 10.
The method must have only one parameter, here's some examples of calling exponent:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
So output should be:
The power of 10 in 2 is 1024
OR
The power of 10 in 5 is 9765625
Do something like
public static int exp(int pow, int num) {
if (pow < 1)
return 1;
else
return num * exp(pow-1, num) ;
}
public static void main (String [] args) {
System.out.println (exp (10, 5));
}
and do not forget the base case (i.e a condition) which tells when to stop recursion and pop the values from the stack.
Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is exponent == 0, in which case it should return 1. (You can also use exponent == 1 as a base case, in which case it should return the base.)
The following is what my instructor, Professor Penn Wu, provided in his lecture note.
public class Exp
{
public static int exponent(int a, int n)
{
if (n==0) { return 1; } // base
else // recursion
{
a *= exponent(a, n-1);
return a;
}
}
public static void main(String[] args)
{
System.out.print(exponent(2, 10));
}
}
Shouldn't it have 2 parameter and handle exit condition like below?
public static int exponent(int baseNum, int power) {
if(power == 0){
return 1;
}else{
return baseNum * exponent(baseNum, power-1);
}
}
For recursion function, we need to :
check stopping condition (i.e. when exp is 0, return 1)
call itself with adjusted condition (i.e. base * base^(n-1) )
Here is the code.
public class Test
{
public static int exponent(int baseNum, int exp)
{
if (exp<=0)
return 1;
return baseNum * exponent(baseNum, --exp);
}
public static void main(String a[])
{
int base=2;
int exp =10;
System.out.println("The power of "+exp+" in "+base+" is "+exponent(base,exp));
}
}
Don't forget , for each recursive function , you need a base case. A stop condition`
static double r2(float base, int n)
{
if (n<=0) return 1;
return base*r2(base,n-1);
}
I came here accidentally, and I think one could do better, as one would figure out easily that if exp is even then x^2n = x^n * x^n = (x^2)^n, so rather than computing n^2-1 recursions, you can just compute xx and then call pow(x,n) having n recursions and a product. If instead the power is odd, then we just do xpow(x, n-1) and make the power even again. But, as soon as now n-1 is even, we can directly write xpow(xx, (n-1)/2) adding an extra product and using the same code as for the even exponent.
int pow_( int base, unsigned int exp ) {
if( exp == 0 )
return 1;
if( exp & 0x01 ) {
return base * pow_( base*base, (exp-1)/2 );
}
return pow_( base*base, exp/2 );
}