Skip to content
Advertisement

How to use a multiply function to execute an exponent function?

So I had a task to create an add function. Then create a multiply function that does not use operators and uses the add function. Now I need to use this multiply function to create a power(exponent) function. This is my attempt so far:

function add(a, b){
   return a + b;
}
// console.log(add(6, 4))
    
    
function multiply(first, second){
    let i = 0;
    let answer = 0;
    while(i < second){
        answer += add(first, 0);
        i += 1;
    }
    return answer;

}
// let m = multiply(10, 4)
// console.log(m);
    
    
function power(x, n){
    let i = 0;
    let answer = multiply(x, x);
    let total = 1;
    while(i < n){
        total += multiply(x, answer)
        i += 1;
     }
     return total;
}
let p = power(2, 4)
console.log(p)

I seem to be stuck here because any changes I make have not been helpful. Any tips on this one?

Advertisement

Answer

I think what you did there is multiplying n with x^3, and then add 1 to it. Because total equals 1. And answer equals x^2, then multiply(x,answer) will give you x^3. You add x^3 to your total in every iteration, thus total will give you 1+(n*x^3)

I suggest you try this one :

function power(x, n){
    let i = 0;
    let answer = 1;
    while(i < n){
        answer = multiply(x, answer)
        i += 1;
     }
     return answer;
}
Advertisement