Power function with recursion - java - java

Here's the working recursive power function alternative to Math.Pow class:
public class Powers {
public static long pow(long x, long p) {
if (p == 0) {
return 1;
}
if (p % 2 == 0) {
long a = pow(x, (p / 2));
return a * a; //This line
} else {
long a = pow(x, ((p - 1) / 2));
return x * a * a; //This line
}
}
}
If I try to be clever and use as much recursion as possible by changing the lines mentioned above to return pow(a, 2) and return x * pow(a, 2), I get a stack overflow error. I get that it should cause considerably more calls to pow, but I don't think it should loop like it appears to. Can anyone explain me through this? Thanks

Doing this you will get the following sequence of calls:
pow(a, 2) -> pow(a, 1) -> pow(a, 0) -> pow(1, 2) -> pow(1, 1) -> pow(1, 0) -> pow(1, 2) -> ...

You should either debug this with some IDE, or simply add some expression in the beginning of the method:
public static long pow(long x, long p) {
System.out.println ("x = " + x + ", p = " + p);
...
Then, read the output, it will contain the sequence of calls of pow

Related

Raise a number to a power with new formula using recursion

after being up for the whole night and giving up, I decided to ask for some help on here.
Following is giving me a headache.
I need to write a recursive method which raises a number to a power using this formula:
a^n = a^(n%2) * a^(n/2) * a^(n/2) | n > 1
I just can't get my hand behind it, as how to do it with only two parameters.
public class raise {
public int recursiveRaiseModulo(int base, int power) {
}
}
I could really use some help, so thank you in advance!
As I don't want it to look like I haven't tried anything, this is what I've come up with. Well it's quite honestly garbage.
public static void recursiveRaiseModulo(int base, int power, int powerCounter) {
int solution = (int) Math.pow(base, (powerCounter % 2)) * (int) Math.pow(base, (powerCounter / 2)) * (int) Math.pow(base, (powerCounter / 2));
if (power == 0 && powerCounter == 2) {
System.out.println("2. Recursive - Solution: 1");
} else if (powerCounter < power) {
raise.recursiveRaiseModulo(base, power, powerCounter + 2);
} else {
System.out.println("2. Recursive - Solution: " + solution);
}
}
You don't need more than two arguments:
public int recursiveRaiseModulo(int base, int power) {
if (power == 0) {
return 1;
}
int halfPower = recursiveRaiseModulo (base, power / 2);
return (power % 2 == 1 ? base : 1) * halfPower * halfPower;
// a^(n % 2) * a^(n/2) * a^(n/2)
}
Note that a^(n%2) is equal to a when n is odd and equal to 1 when n is even.

How to find gcd(a,b) % p efficiently where p is a prime?

My approach is very simple:
First, Finding gcd(a,b) using Euclid's Algorithm.
Then taking out mod with p=10^9+7
But I need an efficient way (just need the right track not code):
Values of a and b could in between 1 to 10^12 whereas p is a prime 10^9+7
It would be my solution if I had an problem as yours. In my solution, I check the range of long whether it may satisfy 10^12. As you can see the following code, it gives 18, which means it's ok! Nonetheless, I wouldn't prefer Euclid's GCD because it works lumbering recursively. The fact your range is really big gives rise to consuming a host of memory. So, I'd prefer Binary GCD Algorithm.
class Test {
private static final long P = (long)Math.pow(10, 9) + 7;
public static void main(String[] args) {
// Check whether long is suitable in regards to ranges
System.out.println((int)Math.log10(Long.MAX_VALUE));
// Your wish up to 10^12, so it's ok!
int result = calculate(1, (long) Math.pow(10, 12));
System.out.println(result);
result = calculate((long) Math.pow(10, 12), (long) Math.pow(10, 12));
System.out.println(result);
}
public static int calculate(long a, long b) {
return (int)(gcd(a, b) % P);
}
private static long gcd(long p, long q) {
// https://introcs.cs.princeton.edu/java/23recursion/BinaryGCD.java.html
if (q == 0) return p;
if (p == 0) return q;
// p and q even
if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;
// p is even, q is odd
else if ((p & 1) == 0) return gcd(p >> 1, q);
// p is odd, q is even
else if ((q & 1) == 0) return gcd(p, q >> 1);
// p and q odd, p >= q
else if (p >= q) return gcd((p-q) >> 1, q);
// p and q odd, p < q
else return gcd(p, (q-p) >> 1);
}
private static long EuclidianGCD(long a, long b) { return b==0 ? a : EuclidianGCD(b, a%b); }
}
You can check answer of the last one from here. Besides, if you insist on usage of Euclid's GCD, try it, it may be stuck! and IMHO it is not efficient whatsoever.

How do you use conditions in lambda expression in java 8?

I am beginner in programming and I was wondering how you can write lambda expressions with conditions.
public interface MathInterface {
public int retValue(int x);
}
public class k1{
public static void main(String [] args) {
MathInterface f1 = (int x) -> x + 4; // this is a normal lambda expression
}
}
The code above should represent the mathematical function:
f(x) = x + 4.
So my question is how can i write a lambda expression that covers this function:
f(x) =
x/2 (if x is divisble by 2)
((x + 1)/2) (otherwise)
any help appreciated :)
Edit: The answer from #T.J. Crowder was, what I was searching.
MathInteface f1 = (int x) -> (x % 2 == 0) ? x / 2 : (x + 1) / 2;
So my question is how can i write a lambda expression that covers this function...
You either write a lambda with a block body ({}) (what I call a "verbose lambda") and use return:
MathInteface f1 = (int x) -> {
if (x % 2 == 0) {
return x / 2;
}
return (x + 1) / 2;
};
or you use the conditional operator:
MathInteface f1 = (int x) -> (x % 2 == 0) ? x / 2 : (x + 1) / 2;
(or both).
More details in the lambda tutorial.
For that particular function, a ternary would be possible.
(int x) -> x % 2 == 0 ? x/2 : (x+1)/2;
Otherwise, make a block
(int x) -> {
// if... else
}
Inside of which, you return the value
This return an integer :
public static void main(String [] args) {
MathInterface f1 = (int x) -> (x%2 ==0) ? x/2 : ((x + 1)/2);
}
If you feel like being cheeky, you can actually exploit integer division here.
When you divide two integers, the part of the number after the decimal point is automatically dropped. So 5 / 2 = 2.
For that reason, you can get away with just the odd number case:
MathInterface f1 = (int x) -> (x + 1) / 2;
In the case of even numbers, when they are incremented they will become odd, resulting in a .5 which will be dropped automatically.
I wouldn't recommend this approach because it's not clear you (the original programmer) are aware what's going on. Being explicit is better.

Recursive method for x^n optimised for when n is even

I need to write a recursive method using Java called power that takes a double x and an integer n and that returns x^n. Here is what I have so far.
public static double power(double x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
else
return x * (power(x, n-1));
}
This code works as expected. However, I am trying to go the extra mile and perform the following optional exercise:
"Optional challenge: you can make this method more efficient, when n is even, using x^n = (x^(n/2))^2."
I am not sure how to implement that last formula when n is even. I do not think I can use recursion for that. I have tried to implement the following, but it also does not work because I cannot take a double to the power of an int.
if (n%2 == 0)
return (x^(n/2))^2;
Can somebody point me in the right direction? I feel like I am missing something obvious. All help appreciated.
It's exactly the same principle as for x^n == x*(x^(n-1)): Insert your recursive function for x^(n/2) and (...)^2, but make sure you don't enter an infinite recursion for n == 2 (as 2 is even, too):
if (n % 2 == 0 && n > 2)
return power(power(x, n / 2), 2);
}
Alternatively, you could just use an intermediate variable:
if (n % 2 == 0) {
double s = power(x, n / 2);
return s * s;
}
I'd probably just handle 2 as a special case, too -- and avoid the "and"-condition and extra variable:
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2) return x * x;
if (n % 2 == 0) return power(power(x, n / 2), 2);
return x * (power(x, n - 1));
}
P.S. I think this should work, too :)
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
if (n == 2) return x * x;
return power(x, n % 2) * power(power(x, n / 2), 2);
}
When n is even, the formula is exactly what you wrote: divide n by two, call power recursively, and square the result.
When n is odd, the formula is a little more complex: subtract 1 from n, make a recursive call for n/2, square the result, and multiply by x.
if (n%2 == 0)
return (x^(n/2))^2;
else
return x*(x^(n/2))^2;
n/2 truncates the result, so subtraction of 1 is not done explicitly. Here is an implementation in Java:
public static double power(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
double pHalf = power(x, n/2);
if (n%2 == 0) {
return pHalf*pHalf;
} else {
return x*pHalf*pHalf;
}
}
Demo.
Hint: The ^ operation won't perform exponentiation in Java, but the function you wrote, power will.
Also, don't forget squaring a number is the same as just multiplying it by itself. No function call needed.
Making a small change to your function, it will reduce the number of recursive calls made:
public static double power(double x, int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
if (n % 2 == 0) {
double temp = power(x, n / 2);
return temp * temp;
} else {
return x * (power(x, n - 1));
}
}
Since
x^(2n) = (x^n)^2
you can add this rule to your method, either using the power function you wrote, as Stefan Haustein suggested, or using the regular multiplication operator, since it seems you are allowed to do that.
Note that there is no need for both the base cases n=1 and n=0, one of them suffices (prefferably use the base case n=0, since otherwise your method would not be defined for n=0).
public static double power(double x, int n) {
if (n == 0)
return 1;
else if (n % 2 == 0)
double val = power(x, n/2);
return val * val;
else
return x * (power(x, n-1));
}
There is no need to check that n>2 in any of the cases.
This just reminds me more optimisation could be done
and this following code.
class Solution:
# #param x, a float
# #param n, a integer
# #return a float
def pow(self, x, n):
if n<0:
return 1.0/self.pow(x,-n)
elif n==0:
return 1.0
elif n==1:
return x
else:
m = n & (-n)
if( m==n ):
r1 = self.pow(x,n>>1)
return r1*r1
else:
return self.pow(x,m)*self.pow(x,n-m)
what is more intermediate result could be memorised and avoid redundant computation.

Reducing recursive calls on pow recursion method?

Had a question on how to reduce the amount of recursive calls on a self implementation of the pow method. Here is what I wrote, can this be improved?
public static int pow(double a, int b) {
boolean isNegative = false;
if(b < 0) {
isNegative = true;
}
if(b == 0) {
return 1;
}
else if(b == 1) {
return (isNegative ? (1 / b) : b);
}
return (isNegative ? ((1 / b) * (1 / b) * pow(a, b + 2)) : (b * b * pow(a, b - 2)));
}
Yes, it can be improved.
Think about it this way:
If b is even, then a^b = a^(b/2) * a^(b/2).
If b is odd, then a^b = a^(b/2) * a^(b/2) * a (where / means integer division).
Code (brain-compiled, coffee hasn't kicked in yet, etc.):
public static double pow(double a, int b) {
if (b < 0)
return 1 / pow(a, -b);
if (b == 0)
return 1;
double halfPow = pow(a, b/2);
if (b % 2 == 0)
return halfPow * halfPow;
else
return halfPow * halfPow * a;
}
This gives you O(log b) recursive calls, as opposed to O(n) in your solution.
Have a look at memoization.
EDIT: Fundamentally, you've got three problems:
The code doesn't work (as of the edit, it now completely ignores a)
The code is too complicated
The code is recursing more than you want it to
Trying to fix the third of these without fixing the first is pointless.
Your first port of call should be some unit tests. They will prove very quickly that your code is currently broken, and give you some confidence that when you've fixed it, you can then change it and know whether or not you've broken anything.
Then you should aim to simplify it. For example, you could easily start your method with:
if (b < 0)
{
return 1 / pow(a, -b);
}
... then you don't need to worry about negative values of b any more.
Finally you can look at what you've got left and try to turn a recursive solution into an iterative solution.

Categories

Resources