recursive method for exponent of a fixed power - java

Is it possible to create a recursive method that takes a single int as a parameter and returns the passed int to the power of 10?
this is what I have so far, but I get StackOverFlow error:
public static int exponent(int baseNum) {
return baseNum * exponent(baseNum);
}

You forgot to tell the recursive function when to stop recursing. It'll just go forever, which is why you get a stack error.
public static int exponent(int baseNum, int exp) {
if (exp == 0)
return 1;
else
return baseNum * exponent(baseNum, --exp);
}
Now you can get 32^10 by calling:
exponent(32, 10);
And if you want a specialized function to raise a number to the power of ten then you can overload the exponent method:
public static int exponent(int baseNum) {
return exponent(baseNum, 10);
}
Only works with exponent values >= 0, of course.

Related

Use recursion in Java to returns the binary logarithm of a given number

This is the Screenshot of The problem that i'm Solving:
This is my code, It's working fine but problem is If n<=0 i want to return "Undefined" at the same method But as you can see my method return type is int. So how can i do that?
public static void main(String[] args) {
System.out.println(recursiveBinaryLog(1));
System.out.println(recursiveBinaryLog(8));
System.out.println(recursiveBinaryLog(0));
System.out.println(recursiveBinaryLog(-2));
}
static int recursiveBinaryLog(int n) {
if (n <= 0)
return 0;
else
return (1 + recursiveBinaryLog(n / 2));
}
To have method recursiveBinaryLog return a String instead of an int, do the recursion in a separate method.
Nothing in the linked problem states that it is the recursiveBinaryLog method itself that has to be recursive, only that you have to use recursion to solve the problem, using the given algorithm.
static String recursiveBinaryLog(int n) {
if (n <= 0)
return "Undefined";
return String.valueOf(recursiveBinaryLog0(n));
}
private static int recursiveBinaryLog0(int n) {
return (n == 1 ? 0 : 1 + recursiveBinaryLog0(n / 2));
}

Issue with recursion because thread suspension

I was playing around with a few practice problems in Java. I wrote a recursive program for program given below. My solution is right except for the suspended (which I believe) gets back to active state and changes the value of the recursive method. I have also added a screenshot of Eclipse in debug mode where the thread stack is shown.
package com.nix.tryout.tests;
/**
* For given two numbers A and B such that 2 <= A <= B,
* Find most number of sqrt operations for a given number such that square root of result is a whole number and it is again square rooted until either the
* number is less than two or has decimals.
* example if A = 6000 and B = 7000, sqrt of 6061 = 81, sqrt of 81 = 9 and sqrt of 9 = 3. Hence, answer is 3
*
* #author nitinramachandran
*
*/
public class TestTwo {
public int solution(int A, int B) {
int count = 0;
for(int i = B; i > A ; --i) {
int tempCount = getSqrtCount(Double.valueOf(i), 0);
if(tempCount > count) {
count = tempCount;
}
}
return count;
}
// Recursively gets count of square roots where the number is whole
private int getSqrtCount(Double value, int count) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
++count;
getSqrtCount(sqrt, count);
}
return count;
}
public static void main(String[] args) {
TestTwo t2 = new TestTwo();
System.out.println(t2.solution(6550, 6570));
}
}
The above screenshot is from my debugger and I've circled the Thread stack. Can anyone try and run the program and let me know what the problem is and what would be the solution? I could come up with a non recursive solution.
Your recursion is wrong, since the value of count will return in any case 0 or 1 even if it goes deep down into recursive calls. Java is pass by value, meaning that modifying the value of a primitive inside of a method wont be visible outside of that method. In order to correct this, we can write the following recursion:
private int getSqrtCount(Double value) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
return getSqrtCount(sqrt) + 1;
}
return 0;
}
Your code is wrong, you should have
return getSqrtCount(sqrt, count);
instead of
getSqrtCount(sqrt, count);
Otherwise the recursion is pointless, you're completely ignoring the result of the recursion.

How to recursively calculate a number raised to a power?

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

Java recursion 1234 to 4321 for example

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);
}

Recursive Exponent Method

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 );
}

Categories