Domanda

I need to write a method that will take a base and raises it to any integer power, positive or negative. It can be assumed that the base will not be 0.

In the method I need to call a recursive method and use it.

Here is the previous recursive method I need to use:

 public static double nonNegInt(double base, int pow)
{
    if (pow == 0)
    return 1;
    else
     return base * nonNegInt(base,pow-1);   
}

So my question is, can someone please help or show me how to write the method I need?

I know the current method is fine, but I need to call it in another method. When I do this I am getting a runtime error

È stato utile?

Soluzione

Your method is a good start, although you will need to handle negative exponents as stated in your requirements. Take advantage of the fact that x^(-n) = 1.0 / x^n.

Altri suggerimenti

This is how you handle negative values too:

public static double nonNegInt(double base, int pow)
{
    if (pow == 0)
        return 1;
    else if(pow < 0)
        return (1 / nonNegInt(base, -pow));
    else
        return base * nonNegInt(base,pow-1);   
}

Running it:

public static void main(String args[])
{
     double result = nonNegInt(4,-1);
     System.out.println(result);  //Will print 0.25
}

Of course you should give it a meaningful name, since now it does handle negative cases.

public BigDecimal exp(BigDecimal base, BigInteger pow) {

    if(base == null || base.intValue() == 0 ) return BigDecimal.ZERO;

    BigInteger absPow = pow.abs();

    if(absPow.intValue() == 0) return  BigDecimal.ONE;

    if(absPow.intValue() == 1) return  pow.intValue() > 0 ? base :
                                            BigDecimal.ONE.divide(base, MathContext.DECIMAL128);

    if(absPow.intValue() == 2) return  pow.intValue() > 0 ? base.multiply(base):
                                            BigDecimal.ONE.divide(base.multiply(base), MathContext.DECIMAL128);

    BigInteger i = BigInteger.ONE;
    BigDecimal result = base;
    HashMap<BigInteger, BigDecimal> history = new HashMap<>();
    history.put(i, result);

    while (i.compareTo(absPow) < 0) {

        if(i.add(i).compareTo(absPow) <= 0) {

            i = i.add(i);
            result =  result.multiply(result);
            history.put(i, result);

        } else {

            BigInteger diff =  absPow.subtract(i);

            for (; diff.intValue() > 0 &&  !history.containsKey(diff); diff = diff.subtract(BigInteger.ONE));

            i = i.add(diff);
            result =  result.multiply(history.get(diff));
            history.put(i, result);
        }

    }


    return pow.intValue() > 0 ? result : BigDecimal.ONE.divide(result, MathContext.DECIMAL128);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top