How to calculate for n root of a number in JS? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 4

How to calculate for n root of a number in JS?

For example : the n root of 32 where n = 5 The answer is 2, because 2×2×2×2×2 = 32. If square root, we can use the Math.sqrt, how about something like the example above?

15th Aug 2020, 2:20 PM
No Name
4 Respuestas
+ 11
You can use Math.pow, because the root is the inverse of the power, so for example Math.pow(32,1/5) should give you 2.
15th Aug 2020, 2:44 PM
Dominik Vladař
Dominik Vladař - avatar
+ 2
well I was interested to solve this problem by myself. Here's my attempt https://code.sololearn.com/W3o81D15Sava/?ref=app
15th Aug 2020, 4:41 PM
Artur
Artur - avatar
+ 2
The only problem is decimal numbers. I used Math.floor there, so my function could return something (regardless inexact value). But works fine with integers.
15th Aug 2020, 4:44 PM
Artur
Artur - avatar
+ 2
It throws error sometimes btw "Maximum call stack size exceeded". Well it's definitely worst solution ever. I'm just not that good with JS yet 🤣
15th Aug 2020, 4:48 PM
Artur
Artur - avatar