2023-05-23

 23 May 2023

Implement Integer Exponentiation

Taken from DailyCodingProblem

Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.

Do this faster than the native method of repeated multiplication.

Solution

This is the answer I came up with:

const exponent = (x: number, y: number): number => x ** y

const custom = (x: number, y: number): number => {
  let result = x
  for (let _ = 1; _ < y; _++) {
    result *= x
  }
  return result
}

Both functions handle exponentiation: the exponent function does it using the exponential operator, and the custom function implements it arithmetically. The custom function is probably the more correct answer, but both functions are faster when tested against the native Math.pow() method.

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/MYewdgzgLgBGCGUCWA3ApjAvDAFADwC44BXAWwCM0AnAGhgE8iwzKqBKJl6rAPhgFlEACwB0ABxAB3fHXpsAsACgloSLDR4JYNGFjZ8nCtVmHWHEkaq8YeGACo7DJSvDQYwYtBCksuQhdYTAOpzZktrAG8lGBgAGzRYKjQIYli9G2iYADMQKxx42AB9XwBGAG4YYoAeBgrCgGp6thgoxRiYpJS0+2w8TIBfTKSoYiowGE7UqCVB5UVVN1IEoRAAEwhfAG0EZHQ6DS0dKDoPL1IAXWd511gkXTQAc2oABXgkKggiAEEqKnh6KphVibc58bCbTKbACsNCh5xokKhAAZYUj4ZCSsiaABmNFKS5zAD0diuABUhEgNkd3hgskh4nA0Gh1jAoCAYJQJsRxncYPAYABhAAyAEkYJ47g9WRAALRgNZoJSUYDwTwYUn0MRoADKwCoSDEsGesX+DyoIG5qxgknpsTgIFgEBWkncrhA8REyCWE2SUwgV218FIYgZFqgYmIUAIV02MBhcZgBJ2qDQRCRIhKAA4AEykf2KA7gI5pkRIqElPMqTxs0glpEAdlz+djWLjSMTSmT6DrJQr+cL2l0daRAE5K-Nq94e1Dx7HMSiYLiO4ou6mYOmkX2lAPi+vS0jM+PTjXh2PmzB53Ql0nECm6wAWbHjndDvdIg9Hye1t+92dtujIsuq6ns+mhFq+G5lp+ZzDgAbH+8ZQkBt7dj+T79mBg5Rm+H75seU44fe45KHYhIuGoMBLPAKRJL4ODwL8-zfIxAJAtQPAnPAsSxOQ8DAAA1kQ8BgHIkSZAs7poJ6SBLDgKrcbxAkiAgSwKG07hcTxfH8fRLGbGidAMX89CbCU5xqTEEkel6aAAKJgKscmaYp-HKUGaBqbMSg5HkCywGIbxWCAWQwHcUCPC8gUQM0rSWW6HqxCADw4AF7wWZRyxrBAIg+bZfFCDgSxQCsVqYHwVE0WgKWBXQRUlWwnlXIShIwAAStQ3KheMSToB8GDKqqEAYJIDGkMQYiEiqwBCGghIJMA3m5LgfkwKlQUhWFEVUK87zZT11BDTgDUtOJ8VSYlyVreldVZTluR5dNhWZaV5VoNRoxVWttXPQ1MxKEAA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems