Denver
Denver

Reputation: 147

Doing exponential operation using only addition in Java

I'm having trouble making this program. Is it possible to write a program by getting the exponential value without using *, ^, Math.pow? Example I have base of 2 and the exponent is 3.

Q1. what operation should I used to help the addition to come up with the correct result?

Q2. addition is enough?

Upvotes: 1

Views: 1718

Answers (2)

Jadiel de Armas
Jadiel de Armas

Reputation: 8802

Yes, it is possible to only use addition to do exponentiation. Remember that multiplication is the repetition of addition many times, and that exponentiation is the repetition of multiplication many times.

For example, you could write the following function that will exponentiate a number:

double exp(long base, long exponent) {

    //when the exponent is zero
    if (exponent == 0) return 1.0;

    long result = base;
    long exponent_abs = Math.abs(exponent);

    //repeating multiplication many times to achieve exponentiation
    for (int i = 2 ; i <= exponent_abs ; ++i) {

        result = multiply(result, base);
    }

     //if the exponent is positive, return result you found.
     if (exponent > 0) return result;
     //if it is negative, return a fraction.
     return 1/((double)result);
  }

//repeating addition many times to achieve multiplication.
long multiply(long number1, long number2){
    long result = number1;

    for (int i = 1; i < number2; ++i){
        result += number1;
    }
    return result;
 }

Note that the function returns a double value, since if your exponent is negative, the result cannot be expressed with an integral type.

Upvotes: 1

engineercoding
engineercoding

Reputation: 832

Why can't you use those functions of the language? Anyway:

public int pow (final int base, final int exponent) {
  int result = base;
  for (int i = 1; i < exponent; i++)
     for (int j = 0; j < base; j++)
         result += base;
  return result;
}

This obviously only works for integers (or longs really), if you have a floating value as exponent I dont think you can avoid ^ or Math.pow

Note that I have not tested this but should work along the line of this, I might have messed up somewhere.

You should also note thate x^0=1, so add an extra check there. And this only works with signed ints, as this algorithm is not made for negatives

Upvotes: 0

Related Questions