Search code examples
javaexponential

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?


Solution

  • 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.