I'd like to change this exponentiation method (n is the exponent):
public static double exponentiate(double x, int n) {
counter++;
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return x * exponentiate(x, n - 1);
}
}
I'd like to change the method to make it more efficient, so the method is not opened n times but maximum (n/2+1) times WITHOUT using the class MATH.
So far I came up with this code:
public static double exponentiate(double x, int n) {
counter++;
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
if (n % 2 == 0) {
n = n-(n-1);
} else {
n = ((n-1) / 2) + n;
}
return ((x * x) * exponentiate(x, n - (n / 2)));
}
}
But somehow it only works for odd n, not vor even n.
Can somebody help?
Thanks!
I think you can optimize the above method to run for O(logn) by calculating exponentiate(x,n/2) once and using it.
Something like this:-
public static double exponentiate(double x, int n)
{
int temp;
if(n == 0)
return 1;
temp = exponentiate(x, n/2);
if (n%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
Hope this helps!
I don't know if this is the solution you search but this is an example of an algorithm that perform exponentiation in O(log(n)) time
public static double exponentiate(double x, int n) {
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return ((n % 2 == 0) ? 1 : x) * exponentiate(x * x, n / 2);
}
}
Related
Guys I want to modify this if or block so dynamically it divide the value x based on what or condition got executed.
public boolean isUgly(int n) {
boolean isUgly=true;
while(n>0)
{
if(n%2==0||n%3==0||n%5==0)
{
n = n/x //<-------- here i want x should be based on the if condition where or is true
}
else {
isUgly=false;
break;
}
}
return isUgly;
}
You looking for something like this?
public static boolean isUgly(int n) {
final int[] uglyPrimes = {2, 3, 5};
boolean isUgly = true;
while (n > 1 && isUgly) {
isUgly = false;
for (int x : uglyPrimes) {
if (n % x == 0) {
n = n / x;
isUgly = true;
}
}
}
return isUgly;
}
Of course, I would just implement it like this:
public static boolean isUgly(int n) {
while (n > 1 && n % 2 == 0)
n /= 2;
while (n > 1 && n % 3 == 0)
n /= 3;
while (n > 1 && n % 5 == 0)
n /= 5;
return (n <= 1);
}
Or this:
public static boolean isUgly(int n) {
for (int x : new int[] { 2, 3, 5 })
while (n > 1 && n % x == 0)
n /= x;
return (n <= 1);
}
All 3 solutions really should have the following added to the beginning of the method, but that's outside the scope of the challenge:
if (n <= 0)
throw new IllegalArgumentException("Invalid value: " + n);
Try the following code, in this way you can divide n depending on the condition, but this method will always return false as in any case, it will execute the else statement for sure. What is your goal?
public boolean isUgly(int n)
{
boolean isUgly=true;
while(n>0)
{
if(n%2==0)
{
n = n/2;
}
else if(n%3==0)
{
n = n/3;
}
else if(n%5==0)
{
n = n/5;
}
else
{
isUgly=false;
break;
}
}
return isUgly;
}
i'm creating recursion method that calculate Log base 2. for log*(1) = should be 0. log*(4) = should be 2. but my method only print out zero and i couldn't figure out the problem.can some one help me?
public static int logCalculator(double n) {
if (n == 1) {
return 0;
} else {
return 1 + logCalculator(n * n);
}
}
This will work for base 2 logs
public static int logCalculator1(double n) {
if (n < 2)
return 0;
return 1 + logCalculator1(n / 2);
}
NOTE: this will round down always and with high numbers is inaccurate, in addition you can make it for all bases like this:
public static int logCalculator(int base, double n) {
if (base > 0) {
if (n < base) {
return 0;
} else {
return 1 + logCalculator(base, (int)(n / base));
}
} return 0;
}
I have implemented a recursive function to find m^n (m raised to the power n).
Now I want to implement the same function but by dividing the problem into two equal parts, like
m^n = m^(n/2) * m^(n/2) = ... (for even n like, m^2, m^4, m^6).
With the implementation below, if I give m = 2 and n = 4, my output is 4 while it should be 16.
public class Recursion {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m,long n) {
if (n > 0)
return m * pow(m, ((n/2) - 1) * pow(m, ((n/2) - 1)));
else
return 1;
}
}
public static long pow(long m,long n)
{
if (n <= 0) {
return 1; // Be lazy first
} else if (n % 2 == 1) {
return m * pow(m, n - 1); // Normal slow strategy
} else { // n even
long root = pow(m, n / 2); // Do not evaluate twice
return root * root;
}
}
Based on a combination of two other answers here, I believe this is the optimal algorithm:
public static long pow(long m, int n)
{
if (n <= 0) {
return 1;
} else if (n == 1) {
return m;
}
int rem = n & 1;
n >>= 1;
if (rem == 0) {
return pow(m * m, n); // x^(2n) = (x^2)^n
} else {
return m * pow(m * m, n); // x^(2n+1) = x * ((x^2)^n)
}
}
i.e. an immediate short-circuit for m^0 or m^1, and a single recursive call for other cases.
EDIT cleaned up slightly and now exactly follows the Wikipedia article on exponentiation by squaring which was algorithmically the same as my previous edit but is now improved by being the even-case being potentially tail recursive on languages that support it.
Try this, it computes by splitting into two parts as required. Also look at http://en.wikipedia.org/wiki/Exponentiation_by_squaring for other methods
class Main {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m, long n) {
if (n > 1)
return pow(m, (n / 2)) * pow(m, (n - (n / 2)));
else if (n <= 0)
return 1;
else
return m;
}
}
This answer adds error reporting on invalid inputs and handles all corner cases:
public long pow(long base, long exponent) {
if (exponent < 0) {
if (base == 1) {
return 1;
} else if (base == -1) {
return exponent % 2 == 0 ? 1 : -1;
} else {
throw new ArithmeticException("Negative exponent");
}
} else if (exponent == 0) {
if (base == 0) {
throw new ArithmeticException("0**0 is undefined");
} else {
return 1;
}
} else {
long root = pow(base, exponent/2);
long result = root * root;
if (exponent % 2 != 0) {
result *= base;
}
return result;
}
}
Technically this computes the result truncated to fit in a long. To detect overflow, the multiplications should be replaced with something like this.
For a non-recursive solution, replace the final else-block with
long result = 1;
while (exponent != 0) {
if (exponent % 2 != 0) {
result *= base;
}
base *= base;
exponent /= 2;
}
return result;
if you add up you ms you have
1+n/2-1+n/2-1
which reduces to
n - 1
Also, you have misplaced a few parenthesis, so you are not actually multiplying where you think you are. You are multiply the result of pow((n/2) -1) to the partialnin your firstpow` call.
I want to find the sum of numbers that is divisible by x using recursive method
Ex if n= 10, x=3, the code should return sum of 3+6+9
Write a recursive method sumDivByX(n, x), which finds the sum of all
numbers from 0 to n that are divisible by x.
I asked my teacher about it and he told me "Firstly, total should be global. You should return 0 if n or x == 0. I only care if n is divisible by x. So I only add n to total (total+=n) if (n%x==0) otherwise do nothing. And do recursion sumDivByX(n-1,x) and return total as usual." I tried to correct it.
public static int sumDivByX(int n, int x) {
int total = 0;
if (n == 0 || x == 0) {
return -1;
}
if (n % x >= 1) {
return total = 0;
} else if (n % x == 0) {
return total += n;
}
return total + sumDivByX(n - 1, x);
}
When I run the program I get 0.
Eliminate the returns inside your second and third if statements
public static int sumDivByX(int n, int x) {
int total = 0;
if (n == 0 || x == 0) {
return 0;
}
if (n % x >= 1) {
total = 0;
} else if (n % x == 0) {
total += n;
}
return total + sumDivByX(n - 1, x);
}
For a cuter, more compact version
public static int sumDivByX(int n, int x) {
if (n == 0 || x == 0) {
return 0;
}
return (n % x == 0 ? n : 0) + sumDivByX(n - 1, x);
}
Note - depending on the semantics you intend, you might want to have separate checks for x<=0 (possibly and error?) and n==0 (base case).
Step through your code and you'll see that it never recurses when n ==10 and x==3, since (10 % 3 == 1)
When a method gets to a "return" statement it ends, in your case at the second if.
Your total is initialized by 0 everytime the method runs, so you should consider making it global.
Your method generates an exception if you try to use negative numbers as paramethers
Try this:
int total=0;
public static int subDivByX(int n, int X) {
if (n>0 && x>0) {
if (n%x==0){
total += n;
}
return sumDivByX(n-1,x);
}
else return -1;
}
This seems to work
private static int sumDivByX(int n,int x) {
if (n < x || x < 1 ) {
return 0;
}
int d = n/x;
return (x * d) + sumDivByX(n - x , x);
}
Recursion could cause a stackoverflow.
public class MultiplyViaRecursion{
public static void main(String[] args){
System.out.println("8 * 9 == " + multiply(8, 9));
System.out.println("6 * 0 == " + multiply(6, 0));
System.out.println("0 * 6 == " + multiply(0, 6));
System.out.println("7 * -6 == " + multiply(7, -6));
}
public static int multiply(int x, int y){
int result = 0;
if(y > 0)
return result = (x + multiply(x, (y-1)));
if(y == 0)
return result;
if(y < 0)
return result = -multiply(x, -y);
return result;
}
}
My question is very simple and basic, why after each "if" the "return" still cannot pass the compilation, error shows missing return.
To put it simply: the Java compiler isn't that smart. It can't deduce that one of your three if statements must evaluate to true. And since the compiler believes there is a chance all the if conditions can fail, it thinks it's possible to go beyond the if blocks, at which point there is no return statement.
Instead, try using an if else block, like so.
public static int multiply(int x, int y) {
int result = 0;
if (y > 0)
return result = (x + multiply(x, (y - 1)));
else if (y == 0)
return result;
else
return result = -multiply(x, -y);
}
Because the compiler cannot guess that your three IFs cover all the cases.
If you want to simplify the code, you can remove the last IF that is unnecessary :
public static int multiply(int x, int y){
int result = 0;
if(y > 0)
return result = (x + multiply(x, (y-1)));
if(y == 0)
return result;
return result = -multiply(x, -y);
}
By the way, you can also remove the result variable :
public static int multiply(int x, int y){
if(y > 0)
return (x + multiply(x, (y-1)));
if(y == 0)
return 0;
return -multiply(x, -y);
}