Reputation: 288
The question which is suggested it is a question which is based on calculating fractional power of number but I wanted it simply in integer form.The function power is showing the powers correctly of a number raised to power b but it is not stopping as expected it should be.When I try to return the sum as return sum at the end of function power it is just loading and showing nothing please help me.Any help will be greatly appreciated.I cant use the built in pow() function.Thanks.
function power(a, b) {
a = parseInt(a);
b = parseInt(b);
var sum = 1;
var result;
var pow = 1;
for (var i = 1; i <= b; i++) {
pow = 1;
if (i == 1) {
pow = a * i;
sum = 1;
} else {
i--;
pow = a * i;
sum = sum * pow;
alert(sum);
}
}
}
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
var answer = power(a, b);
alert("a^b is equal to : " + answer);
Upvotes: 1
Views: 292
Reputation: 377
If you are interested in recursive function call, check this out.,
var power = function(a, b)
{
a = parseInt(a);
b = parseInt(b);
if (b === 0)
{
return 1;
}
else
{
return a * power(a, b-1);
}
};
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
alert("the result "+ a + " ^ " + b + " is " + power(a, b));
Upvotes: 2