finding nth root of a number by using divide and conquer method

你离开我真会死。 提交于 2019-12-01 12:10:33

Let me tell you how you can use divide and conquer for finding square root. The nth root would be similar.

For a given number x, you need to search for it's square root between 0 and x. Divide it by 2 = x2. If the x2 * x2 < x then your search space moves to x2 -> x or else it will be 0 -> x2. If x2 * x2 matches x then your square root is x2. Similar technique for nth root.

For those not doing numerical experiments: use the <cmath> functions sqrt and cbrt (cube-root) to construct the any root that is factorable by 2 and 3. For example, the 4th root is sqrt(sqrt(x)) and the 6th root is sqrt(cbrt(x)). If you need something for general use you can construct a recursive function which calls sqrt and cbrt appropriately.

I'm guessing this will give a faster and more accurate answer than pow, if that matters. If it doesn't, just use pow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!