3

C has sqrt() and cbrt(), but those are only the second and third roots. What if the root is an arbitrary number? What if I need the 57nth root?

  • If there's no standard function to do what you need, and you can't find a third-party library containing that functionality (or you're not able to use such a library for some reason) then you have to write it yourself. – Some programmer dude Feb 10 '21 at 17:20
  • Simple answer: you need to write it yourself (or if you aren't the type of person that does that then just do [this](https://stackoverflow.com/a/20730080)) – Lakshya Raj Feb 10 '21 at 17:48
  • @LakshyaRaj @Some programmer dude -- Guys, guys, honestly. "Write it yourself" is pretty poor advice. Any kind of mathematical function is tricky once one gets into details, but luckily this is a well-known problem with a well-known solution (namely `pow`). – Robert Dodier Feb 10 '21 at 18:10
  • @RobertDodier: Yes, that is why I gave an alternative option. I'm sorry if that sounded a bit harsh. Seems like the accepted answer used the one from my link. – Lakshya Raj Feb 10 '21 at 18:11
  • @RobertDodier *Anything* that doesn't exist or can't be used (due to licensing reasons perhaps) is going to be "tricky". And then the only available solution is to write it yourself (or hire someone to write it for you), there's simply no way around that. And neither of the answers to this question can be used without *writing it into the code*. Sure it could be copy-pasted but it's still a way of writing it oneself, especially if it is put into its own function. – Some programmer dude Feb 11 '21 at 05:09

2 Answers2

6

Use the pow function, taking advantage of the fact that getting the 57 root is the same as raising to the power of 1 / 57.

More generically, to get the y root of x:

double result = pow(x, 1.0 / y);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Oh my god, if it's that easy to get a root with `pow()`, then there doesn't even need to be `sqrt` and `cbrt`. Like arbitrary natural `log()`, `log2()`, and `log10`. Instead, the library should include `root(index, radicant)` and `log(base, n)` instead of a bunch of arbitrary variants. –  Feb 11 '21 at 21:23
  • @user15170464 Those log function are optimized for their specific base. And `log(base,n)` can be trivially implemented as `log(n)/log(base)` (or `log2(n)/log2(base)`, etc.). – dbush Feb 11 '21 at 21:27
  • Which is better to implement my own `log`? –  Feb 11 '21 at 21:30
2

You should the pow(x,n) function instead.

The function definition is as the following: double pow(double x, double y)

So, in that case above, you should write

pow(x, 1.0/57.0);