Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I faced an interview. where I was asked the following question
Write a function in any of programming language that computes the nth power of a number w/o using + * or ^ or declaring a new variable inside the function or using any library function (eg Math lib in java).
I have used pow function of java Math.pow(a, b)
Thanks
They're asking whether you understand recursion. Considering x ^ k for some integer k,
when k < 0, xk = xk+1 / x
when k = 0, xk = 1
when k > 0, xk = xk-1 * x
Turning this into code shouldn't be too bad. Let's use multiplication for now, and take it out later.
double recursivePower(double x, int k) {
if (k < 0) {
return power(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return power(x, --k) * x;
}
}
Now, to get rid of the multiplication. Since n * m = n / (1/m), we can rewrite the last calculation as power(x, --k) / (1/x):
double recursivePower(double x, int k) {
if (k < 0) {
return recursivePower(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return recursivePower(x, --k) / (1 / x);
}
}
Fractional exponents could probably be done in the same style. If they want irrational exponents to be handled in the same way, I'd ask for Google and a fair amount of time to think about the problem.
static public int power(int value, int pow){
if(pow == 0) return 1;
return value * power(value, pow -1);
}
Done in JavaScript:
function power(num,pow){
if (pow == 0) return 1
num /= 1/(power(num,--pow))
return num
}
Call it like:
power(2,0) // -> 1
power(5,2) // -> 25
power(7,3) // -> 343
I feel like inverse division is cheating the no * operator rule, but eh, maybe that's what they were looking for.
I am using java programming language. The interviewer restricted you to declare a new variable inside the method better you pass it to the function. The interviewer didnt restrict you to use division operator (/) so you can use that.
static double getNthPowerOfNumber(double originalNumber,
int power) {
if (power == 0) {
return 1;
}
if (originalNumber == 0) {
return 0;
} else {
originalNumber/=1/getNthPowerOfNumber(originalNumber, --power);
return originalNumber;
}
}
if you want to get 5th power of a number 3 then write System.out.println("4..double..." + getNthPowerOfNumber(4, 1));
Related
The Identity being, xn = (xn/2)2 for all values where n is even and greater than 0.
How would I do this using a recursion method?
I'm finding myself stuck, and this is what I've been working with
public static double power(double base, int power){
if (power == 0){
return 1;
}
else if (power > 0 || power % 2 == 0){
???
}
public class Pow {
public static void main(String $[]){
System.out.println(pow(2,9));
}
public static double pow(double base, int power){
if (power == 0)
return 1;
//even
if((power&1)==0)
return pow(base*base,power/2);
//odd
return base*pow(base,power-1);
}
}
xn = (x2)n/2 if n is even
xn = x*xn-1 if n is odd
Point of using this approach is to compute the power in log(n) because it is dividing the power by two when its even.
You also need to account for the case where power is odd, and ideally also trap for the case when power is negative.
Just so that I'm not giving absolutely everything away, here's a JavaScript implementation:
function power(x, n) {
if (n < 0) {
return undefined; // uh-oh!
} else if (n === 0) {
return 1; // x^0 = 1
} else if (n % 2 === 0) {
const v = power(x, n / 2); // optimisation for even powers
return v * v;
} else {
return x * power(x, n - 1); // general case - x^n = x * x^(n-1)
}
}
You could also include an explicit test for x^1, but the code above works without it because the recursion terminates when it gets to calculating x * (x ^ 0).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My code works perfectly for some floating value such as 125.5:
public class NewClass {
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
NewClass ob = new NewClass();
double n = Input.nextDouble();
double cbrt = ob.Cbrt(n);
System.out.println(cbrt);
}
public double GetSquareRoot(double n, double low, double high) {
double cbrt = (low + high) / 2;
if (cbrt*cbrt*cbrt > n)
return GetSquareRoot(n, low, cbrt);
if (cbrt*cbrt*cbrt < n)
return GetSquareRoot(n, cbrt, high);
return cbrt;
}
public double Cbrt(double n) {
NewClass ob = new NewClass();
return ob.GetSquareRoot(n, 0, n);
}
}
It does not give correct answer when input is:
0.008
or 0.125
or 50
or 100
Then I am getting java.lang.StackOverflowError.
When input is 125.5 or 125 or 8 it gives the correct solution.
Can someone help me?
The error is that this line:
return ob.GetSquareRoot(n, 0, n);
(which is, of course, misnamed) tries to find a solution between 0 and n. However, if 0 < n < 1, then n1/3 > n, so you will never find a solution in the interval (0, n). You'll need to make a special case of this; for example, if 0 < n < 1, you can search the interval (n, 1) instead.
Also, using 0 and n as the bounds won't work for negative numbers, so if you want to make your method more complete and handle those cases, you'll need special cases for those too (probably different for -1 < n < 0 and n < -1).
MORE: After seeing your comment about StackOverflowError, it's occurred to me that you have an additional problem: that you're expecting an exact result. When you put in 0.008, the cube root is 0.2. However, neither 0.008 nor 0.2 can be represented exactly as a floating-point number. The consequence is that if you let cbrt = whatever value is closest to 0.2 that can be represented, then cbrt*cbrt*cbrt won't be exactly 0.008. It can't be exactly 0.008 anyway, since 0.008 can't be represented as a double; however, if n is whatever value is closest to 0.008, then it's likely that cbrt*cbrt*cbrt will not be exactly equal to n, due to roundoff errors. For a calculation like this, it's important that you not compare doubles for equality; instead, compare them using an "epsilon" value, or a margin of error. Thus, after
double cbrt = (low + high) / 2;
you should have something like
if (Math.abs(cbrt*cbrt*cbrt - n) < EPSILON)
return cbrt;
where EPSILON is some small value such as 1E-10. (I've sometimes seen code where EPSILON is computed to be a relative value, i.e. abs(n * RELATIVE_EPSILON), instead of an absolute value.)
Another way to avoid StackOverflowError is to quit when low and high become really close, because by that point you're not going to gain much more accuracy, and you need to make sure you exit the algorithm even if the value of cbrt*cbrt*cbrt is a little bit off. Something like
if (high - low < EPSILON)
return cbrt;
See also What's wrong with using == to compare floats in Java?.
//How about My Solution - Without Recursive
import java.util.Scanner;
public class CubeRoot {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.next();
Boolean negative = false;
if (str.startsWith("-")) {
str = str.substring(1);
negative = true;
}
if (str.indexOf(".") > 0) {
// find the poisition of '.'
int pPos = str.length() - 1 - str.indexOf(".");
String plainStr = (str.substring(0, str.indexOf('.')).concat(str.substring(str.indexOf('.') + 1)));
StringBuffer cStr = new StringBuffer(cubeRoot(plainStr));
if (cStr.toString().equalsIgnoreCase(plainStr))
System.out.println("couldn't compute Cube Root for this :(");
else {
if (cStr.length() > pPos / 3) // devide 3 times to put the '.'
cStr.insert(cStr.length() - pPos / 3, ".");
else {
int cStrLength = cStr.length();
for (int i = 0; i <= pPos / 3 - cStrLength; i++)
cStr = new StringBuffer("0").append(cStr.toString());
cStr.insert(cStr.length() - pPos / 3, ".");
}
String append = (negative) ? new String("-") : new String("");
System.out.println(append + cStr.toString());
}
} else {
System.out.println("Not a floating num");
}
}
private static String cubeRoot(String d) {
Long l = new Long(d);
for (int i = 0; i < l; i++) {
if (i * i * i == l) {
return String.valueOf(i);
}
}
return d;
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I found the The implements of Integer numberOfTrailingZeros method in java as follows
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
It's take me a while to understand, here is my solution :
public static int numberOfTrailingZeros(int i) {
if (i == 0) return 32;
int num = 0;
while ((i & 1) == 0) {
i >>= 1;
num ++;
}
return num;
}
My question is what's the better solution? How can I come up with those implements such as in JDK Integer bitCount,highestOneBit,rotateLeft etc methods?
as I know the JDK's numberOfTrailingZeros use less + opeartor, and will be having higher performance when dealing with '0x70000000','0x60000000', and anything else?
What the java JDK is doing is sort of a binary search in the number to find the number of trailing zeros. It tries to shift the number left by powers of 2 to see if the shifted number becomes 0. If it doesn't, there are some set bits that are too far to the right, so the method keeps that shifted number, decrements the final count, and tries again with the next smallest power of 2.
I was given a beginner assignment based on recursion to calculate the product of any given base and power.
My professor wanted us to use recursion to calculate this using three different methods..
I've done the first two with little problem, however the final recursive function is giving me grief.
(for method power4)
• X^n = ( X^ (n / 2)^2 if n > 0 and n is even
• X^n = X * ( X^ (n / 2)^2 if n > 0 and n is odd
all I need to do is raise power4(x, (n/2)) to the power of 2
I am not allowed to call the math class... I can't think of anyway to raise this function to the power of 2, any help would greatly be appreciated.
PS: I would prefer help or an explanation rather than just the answer if possible
Thanks.
I just need help with the method power4, power2 and power3 already work fine.
CODE:
public int power2(int x, int n)
{
if(n == 0)
answer = 1;
else if (n > 0)
answer = x * power2(x, (n - 1));
return answer;
}
public int power3(int x, int n)
{
if(n == 0)
answer = 1;
else if(n % 2 == 0)
answer = power3(x, (n/2)) * power3(x, (n/2));
else
answer = x * power3(x, (n/2)) * power3(x, (n/2));
return answer;
}
public int power4(int x, int n)
{
if(n == 0)
answer = 1;
//incomplete code from here down
else if (n % 2 == 0)
answer =
else
answer = x *
return answer;
}
Raising a value to the power of two, a.k.a. squaring it, is simply multiplying it by itself. However, DON'T multiply two recursive calls to the function - do something like
result = power4(x, n/2);
answer = result * result;
Then, if it's odd, multiply answer by x.
If you were to try doing this as answer = power4(x, n/2) * power4(x, n/2);, you'd be doubling the amount of work at each level of the recursion by calling the function twice, and completely undo the logarithmic run time.
By the way, are you sure one of your cases isn't supposed to be based on xn = (x2)n/2 or xn = x*(x2)n/2 for n even or odd, respectively? As you've described it, it looks like power3 and power4 are the same.
This might help with raising to the power of 2:
int answer = 0;
for (int i = 0; i < x; i++)
{
answer += x;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
import acm.program.*;
public class Practice3 extends ConsoleProgram
{
public static int powersOf2(int k) {
int x = 0;
while (k < 1000) {
x = k;
k *= 2;
}
return x;
}
public void run()
{
println(powersOf2(1));
println(powersOf2(0));
println(powersOf2(2));
println(powersOf2(-1));
println(powersOf2(3000));
}
I don't think I really get right values from powersOf2. Only 512 is displayed when I run program. And if I run it by each println, it gives me:
512
none
512
none
0
Is there something wrong? or values are correct?
public static int powersOf2(int k){
int x=1;
while (k > 0){
x *= 2;
k--;
}
return x;
}
The method powersOf2 is completely wrong. It will always return the biggest power of 2 less then 1000. You should take into account the input argument and perform as many multiplications by two:
public static int powersOf2(int k){
int x=1;
for (int i = 0; i < k; ++i) {
x *= 2;
}
return x;
}
It won't always return 512. It depends on your initial parameter.
If you pass k as a parameter, it returns k*2^n which is less than 1000 and k*2^(n+1) is more than 1000. (so with parameter 0 method will loop forever)
So if you pass 3, as its parameter it would return 768 and if you pass any number between 501 and 999 the method will be your initial parameter.
For negative number the method multiples the input parameter by 2, until a underflow occurs, if the result of underflow is greater than 1000 it will return the last negative number, otherwise, it will continue the iterations with same exact logic as a positive parameter less than 1000.
So what do you expect your program do?
Your program goes into infinite loop because when you try to call the method with 0 as input. k is always 0 and it is always less than 1000. You need to exclude 0 in your program because it does not make sense having powers of 2 for 0
I think you want to take care of the special cases- for 0, it should be 1, for negative, you should treat it as a negative power, hence you should use double instead of int for your variable. And here is the code:
public class Practice3 extends ConsoleProgram
{
public static double powersOf2(int k) {
double x = 0;
if(k == 0) {
return 1;
}
double answer = 2;
if(k>0){
for(int i = 0; i < k; i++) {
answer *= 2;
}
return answer;
} else {
answer = 1;
for(int i = 0; i > k; i--) {
answer /= 2;
}
return answer;
}
}
You are always multiplying k by 2 until it exceeds 1000. So, for all 1000 > k > 0 it returns 512, otherwise it returns 0.
public static int powersOf2(int k){
int x=1;
for (i=0; i < k; i++){
x*=2;
}
return x;
}