أحمد الجوني
أحمد الجوني

Reputation: 11

How can I make power method?

I want make the power method I made this :

var x = 2, n = 3, i;
for (i = 1; i < n; i++) {
  x = x * x;
}
console.log(x);

This gives 16 as result but expected is x^n = 8.

Upvotes: 0

Views: 131

Answers (3)

weirdpanda
weirdpanda

Reputation: 2626

Try recursion:

const power = ( base, exponent ) => {
    if( exponent === 0 ) return 1; 
    else return base * power( base, exponent - 1 );
};

Or try the normal for loop:

const power = ( base, exponent ) => {
    let result = 1;
    for( let i = 0; i < exponent; i++ )
        result *= base;
    return result;
};

The reason yours isn't working is because it tries to compute x = x^2 for n steps. Hence, the calculation is 2^2 = 4^2 = 16. The above code, instead, has a result variable which multiplies the base an exponent number of times.

Upvotes: 2

thexpand
thexpand

Reputation: 641

You can use the built-in method Math.pow(number, power).

console.log(Math.pow(2, 10));

Upvotes: -2

clemens
clemens

Reputation: 17712

This function doesn't compute the power because it squares the intermediate results. You should use a separate variable like this:

var x= 2 ,n= 3, i;
var y = x;
for(i=1;i<n;i++){
    x *= y;
}
console.log(x);

Upvotes: 3

Related Questions