通过使用分而治之的方法,找到了一些n次方根 [英] finding nth root of a number by using divide and conquer method

查看:158
本文介绍了通过使用分而治之的方法,找到了一些n次方根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要如何获得一定数目的n次方根的帮助。

I need help on how to get nth root of some number.

用户输入数n和一些他想要的根源。我要解决这个问题,而不CMATH lib和与分而治之的方法。

User enters number n and number he wants root of. I need to solve this without cmath lib and with divide and conquer method.

下面是我的code不工作尚未:

Here's my code that doesn't work yet:

#include<iostream>
using namespace std;

float pow(float a,float c){
    if (a == 0)
        return 0;
    else if(a == 1)
        return 1;
    else{
        float p = pow(a,(c/2));
        if(c%2)
            return p*p*a;
        else
            return p*p;
    }
}

int main(){
    float a,b;
    float c;
    cout << "Enter positive number:(base)" << endl;
    do{
        cin >> a;
    }while (a < 0);
    cout << "Enter number: (root)" << endl;
    cin >> b;
    c = 1/b;
    cout << "Result:"<<pow(a,c) << endl;
    system("pause");
    return 0;
}

对如何处理这个问题的任何想法会更有益。

Any ideas on how to approach this problem would be more than useful.

推荐答案

让我来告诉你如何使用分而治之寻找平方根。 n次方根是相似的。

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

对于一个给定数量 X ,你需要寻找它的 0 平方根和 X 。通过 2 = X2 把它。如果 X2 * X2 &LT; X 那么你的搜索空间移动到 X2 - &GT; X ,否则这将是 0 - &GT; X2 。如果 X2 * X2 匹配 X 那么你的平方根 X2 。类似的技术n次方根。

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.

这篇关于通过使用分而治之的方法,找到了一些n次方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆