4

I've been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class... or method still can't distinguish the two am not so good with theory. So i wrote this..

public static void main(String[] args) {

    int a = 2;

    int b = 31;

    System.out.println(Math.pow(a, b));

    }

Then i wanted to make my own Math.pow without using loops i wanted it to look more simple than loops, like using some type of Repeat I made a lot of research till i came across the commons-lang3 package i tried using StringUtils.repeat
So far I think this is the Syntax:-

public static String repeat(String str, int repeat)
    StringUtils.repeat("ab", 2);

The problem i've been facing the past 24hrs or more is that StringUtils.repeat(String str, int 2); repeats strings not out puts or numbers or calculations.
Is there anything i can do to overcome this or is there any other better approach to creating a function that calculates powers?
without using loops or Math.pow

This might be funny but it took me while to figure out that StringUtils.repeat only repeats strings this is how i tried to overcome it. incase it helps

 public static int repeat(int cal, int repeat){
     cal = 2+2;
     int result = StringUtils.repeat(cal,2);
     return result;
}  

can i not use recursion maybe some thing like this

public static RepeatThis(String a)
{
     System.out.println(a);
     RepeatThis(a);
} 

just trying to understand java in dept thanks for all your comments even if there were syntax errors as long as the logic was understood that was good for me :)

Mo Arctic
  • 193
  • 2
  • 2
  • 7
  • The fact that it's called `String`Utils should give you a hint that it's for working with `String`s and not numbers... – Boris the Spider Oct 17 '13 at 11:55
  • If you are trying to re-implement Math.pow() for learning purposes then fine but otherwise just stick to this default implementation. You will not be able to write a better one yourself. Using non-standard implementations only add unnecessary complexity to your code and makes it harder for other people to understand it. – Muton Oct 17 '13 at 12:06
  • @BoristheSpider yea you're right. – Mo Arctic Oct 17 '13 at 12:32
  • @Muton yes it's obviously for learning purpose. I don't think there is any point to re-implementing something like Math.pow() atleast not with my level of skills. but still thanks for the advice, its always good to be reminded of such things :) – Mo Arctic Oct 17 '13 at 12:33

10 Answers10

13

Another implementation with O(Log(n)) complexity

public static long pow(long base, long exp){        
    if(exp ==0){
        return 1;
    }
    if(exp ==1){
        return base;
    }

    if(exp % 2 == 0){
        long half = pow(base, exp/2);
        return half * half;
    }else{
        long half = pow(base, (exp -1)/2);
        return base * half * half;
    }       
}
Vaibhav Fouzdar
  • 199
  • 1
  • 4
8

Try with recursion:

int pow(int base, int power){
    if(power == 0) return 1;
    return base * pow(base, --power);
}
user987339
  • 10,519
  • 8
  • 40
  • 45
  • can i not use recursion maybe something like this public static RepeatThis(String a) { System.out.println(a); RepeatThis(a); } – Mo Arctic Oct 17 '13 at 12:05
  • You can do it also by simulating stack. You should also remember that every iteration can be converted to recursion, but not every recursion can be converted to iteration. Recursive function are getting more and more important with a rise of functional programming, so give it a try. – user987339 Oct 17 '13 at 12:08
  • 1
    @Craiz if you want to carry out an operation a parameterised number of times you have to either loop or recurse. There is no other way of doing it. What do you think `StringUtils.repeat` does? – Boris the Spider Oct 17 '13 at 12:10
  • @user thanks a lot am already looking into recursion but its really annoying when you cant get a code done the way you imagined it to be the first time hahaha – Mo Arctic Oct 17 '13 at 12:13
  • @Boris the Spider yes i think i get that now. if you check my question you'll find that i edited it I just added something at the end. I guess was just trying to force that logic into java. Thanks :) – Mo Arctic Oct 17 '13 at 12:17
5

Function to handle +/- exponents with O(log(n)) complexity.

double power(double x, int n){
 if(n==0)
  return 1;

  if(n<0){
      x = 1.0/x;
      n = -n;
  }
 double ret = power(x,n/2);
 ret = ret * ret;
 if(n%2!=0)
   ret = ret * x;
 return ret;

}

1

This one handles negative exponential:

public static double pow(double base, int e) {
    int inc;
    if(e <= 0) {
        base = 1.0 / base;
        inc = 1;
    }
    else {
        inc = -1;
    }
    return doPow(base, e, inc);
}

private static double doPow(double base, int e, int inc) {
    if(e == 0) {
        return 1;
    }
    return base * doPow(base, e + inc, inc);
}
myang
  • 193
  • 1
  • 9
1

I think in Production recursion just does not provide high end performance.

double power(double num, int exponent)
{

double value=1;
int Originalexpn=exponent;
double OriginalNumber=num;

if(exponent==0)
    return value;

if(exponent<0)
{
    num=1/num;
    exponent=abs(exponent);
}

while(exponent>0)
{
    value*=num;
    --exponent;
}

cout << OriginalNumber << " Raised to  " << Originalexpn << " is " << value << endl;
return value;

}

Angelo
  • 61
  • 1
  • 8
0

Sure, create your own recursive function:

public static int repeat(int base, int exp) {
 if (exp == 1) {
  return base;
 }

 return base * repeat(base, exp - 1);
}

Math.pow(a, b)

Math is the class, pow is the method, a and b are the parameters.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

Use this code.

public int mypow(int a, int e){
    if(e == 1) return a;
    return a * mypow(a,e-1);
}
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
0

Here is a O(log(n)) code that calculates the power of a number. Algorithmic technique used is divide and conquer. It also accepts negative powers i.e., x^(-y)

import java.util.Scanner;

public class PowerOfANumber{
        public static void main(String args[]){
                float result=0, base;
                int power;
                PowerOfANumber calcPower = new PowerOfANumber();
                /* Get the user input for the base and power */
                Scanner input = new Scanner(System.in);
                System.out.println("Enter the base");   
                base=input.nextFloat();
                System.out.println("Enter the power");
                power=input.nextInt();
                result = calcPower.calculatePower(base,power);
                System.out.println(base + "^" + power + " is " +result);
        }   
        private float calculatePower(float x, int y){ 
                float temporary;
                /* Termination condition for recursion */    
                if(y==0)
                        return 1;
                temporary=calculatePower(x,y/2);
                /* Check if the power is even */
                if(y%2==0)
                        return (temporary * temporary);
                else{
                        if(y>0)
                                return (x * temporary * temporary);
                        else
                                return (temporary*temporary)/x;
                }    
        }
}
Var
  • 329
  • 5
  • 14
0

Remembering the definition of the logarithm, this can be done with ln and exp if these functions are allowed. Works for any positive base and any real exponent (not necessarily integer):

x = 6.7^4.4
ln(x) = 4.4 * ln(6.7) = about 8.36
x = exp(8.36) = about 4312.5

You can read more here and also here. Java provides both ln and exp.

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
-1

A recursive method would be the easiest for this :

int power(int base, int exp) {
    if (exp != 1) {
        return (base * power(base, exp - 1));
    } else {
        return base;
    }
}

where base is the number and exp is the exponenet

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
Aneesh
  • 1,703
  • 3
  • 24
  • 34
  • Thanks, forgot the else. – Aneesh Oct 17 '13 at 12:04
  • You don't need an `else` as there is a `return`. There are no brackets which is generally bad practice and the code is unreadable. – Boris the Spider Oct 17 '13 at 12:04
  • I added the brackets. and `else` is mandatory for this function btw otherwise it wont compile as if the condition fails, it will the function will just return whearas it should return a int – Aneesh Oct 17 '13 at 12:07
  • 1
    Nope, look at the other examples. You need an `if` but you can just `return` without an `else`. P.S. I formatted your code, I really don't understand what's so difficult about that. – Boris the Spider Oct 17 '13 at 12:08
  • Other examples work because there are other return statements besides the one in the `if` block. So `int` will be returned even if `if` fails. Ofcourse I can just `return base` without the `else` but isn't that the same thing here? – Aneesh Oct 17 '13 at 12:11