spectatorx spectatorx - 2 months ago 8x
PHP Question

Mathematical root of any two numbers in PHP

I'm trying to create simple advanced calculator just for fun and currently I'm facing a problem.
In PHP we have a function

which let's you calculate just a square root of an number. Thing i want to achieve is to make this calculator count any given root of any given number. For example if user enters "5 to 7" calculator supposed to calculate not square but 7th root of number 5. Any idea how to achieve something like this? Sorry if you misunderstood something, i'm not expert in English about math. Thanks for help in Advance.


Using pow:

function nthRoot($number, $nthRoot) {
    return pow($number, (1/$nthRoot));

So, nthRoot(32, 5) == 2, as anything to the power of (1/N) is the same as taking the Nth root of that number. E.g.,

  • sqrt(4) == 4^(1/2),
  • sqrt(sqrt(16)) == 16^(1/4), where sqrt(sqrt((N)) is the same as saying the square root of the square root, i.e., "the 4th root".