1

I found some problem with JavaScript exponentiation While loop code:

var x = Number(prompt("X:"));
var y = Number(prompt("Y:"));
var count = 1;
var power = 1;
while(count <= y){
 power = power * x;
 console.log (x + " to the power of " + count + " is: " + power);
 count++;
}
This is simple mathematical formula X^Y. In case of X=5 and Y=25 it's going well till Y=23. It looks like there is some problem with X odd numbers. Eg. X=3 and Y=35. Wrong result at Y=34. Missing "1" during multiplication. Can someone explain why it happend?
Dawid
  • 11
  • 1

1 Answers1

0

You better know something about isSafeInteger in js:

3 to the power of 33 is: 5559060566555523

3 to the power of 34 is: 16677181699666568

3 to the power of 35 is: 50031545098999704

console.log(
  Number.isSafeInteger(5559060566555523),
  Number.isSafeInteger(16677181699666568),
  Number.isSafeInteger(50031545098999704)
)

A safe integer is an integer that

can be exactly represented as an IEEE-754 double precision number, and whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.

For example, 2^53 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 2^53 is not a safe integer: it can be exactly represented in IEEE-754, but the integer 2^53 + 1 can't be directly represented in IEEE-754 but instead rounds to 2^53 under round-to-nearest and round-to-zero rounding. The safe integers consist of all integers from -(2^53 - 1) inclusive to 2^53 - 1 inclusive (± 9007199254740991 or ± 9,007,199,254,740,991).

xianshenglu
  • 4,943
  • 3
  • 17
  • 34