DEV Community

Discussion on: Square a number: awful answers only

Collapse
 
lucamattiazzi profile image
Luca
function square(n) {
  with(Math) {
    for (let i = Number.MAX_SAFE_INTEGER; i >= 0; i--) {
      const isSquared = sqrt(i) === n
      if (isSquared) return i
    }
  }
  throw new Error('Number too big to be squared!')
}
Enter fullscreen mode Exit fullscreen mode

note: using with should improve performances since it does not need to access Math each time sqrt is used