Domanda

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 :)

È stato utile?

Soluzione 2

Try with recursion:

int pow(int base, int power){
    if(power == 0) return 1;
    return base * pow(base, --power);
}

Altri suggerimenti

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

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;

}

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

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;

}

Use this code.

public int mypow(int a, int e){
    if(e == 1) return a;
    return a * mypow(a,e-1);
}

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.

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

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.

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top