查找间隔内所有数字的第n个根 [英] Find n-th root of all numbers within an interval

查看:89
本文介绍了查找间隔内所有数字的第n个根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,必须打印一个区间内所有整数的完美平方根。现在我想为n的根。

I have a program which must print perfect square roots of all integer numbers within an interval. Now I want to do that for n-the root.

这是我做的,但我被困在fmod。

Here's what I've done, but I'm stuck at fmod.

#include <iostream>
#include <math.h>
using namespace std;

int nroot(int, int);

int main()
{

    int p, min, max,i;
    double q;

    cout << "enter min and max of the interval \n";
    cin >> min;
    cin >> max;
    cout << "\n Enter the n-th root \n";
    cin >> p;
    i = min;

    while (i <= max)
    {
        if (fmod((nroot(i, p)), 1.0) == 0)
        {
            cout << nroot(i, p);
        }
        i++;
    }
    return 0;
}

int nroot (int i, int p){

    float q;
    q = (pow(i, (1.0 / p)));

    return q;
}


推荐答案

在相反方向。而不是采取间隔中的每个值的第n个根以查看第n个根是否是整数,而是采用间隔的边界的第n个根,并且根据根来计算:

You may want to tackle this in the opposite direction. Rather than taking the nth root of every value in the interval to see if the nth root is an integer, instead take the nth root of the bounds of the interval, and step in terms of the roots:

// Assume 'min' and 'max' set as above in your original program.
// Assume 'p' holds which root we're taking (ie. p = 3 means cube root)
int min_root = int( floor( pow( min, 1. / p ) ) );
int max_root = int( ceil ( pow( max, 1. / p ) ) );

for (int root = min_root; root <= max_root; root++)
{
    int raised = int( pow( root, p ) );
    if (raised >= min && raised <= max)
        cout << root << endl;
}

$ c> loop是处理 min max 直接在根上,一个根。

The additional test inside the for loop is to handle cases where min or max land directly on a root, or just to the side of a root.

您可以从循环中删除测试和计算,通过识别引发边界的循环。这个版本虽然稍微复杂一点,但是实现了这样的观察:

You can remove the test and computation from the loop by recognizing that raised is only needed at the boundaries of the loop. This version, while slightly more complex looking, implements that observation:

// Assume 'min' and 'max' set as above in your original program.
// Assume 'p' holds which root we're taking (ie. p = 3 means cube root)
int min_root = int( floor( pow( min, 1. / p ) ) );
int max_root = int( ceil ( pow( max, 1. / p ) ) );

if ( int( pow( min_root, p ) ) < min )
    min_root++;

if ( int( pow( max_root, p ) ) > max )
    max_root--;

for (int root = min_root; root <= max_root; root++)
    cout << root << endl;

如果你真的关注性能(我怀疑你不是这种情况)可以用完全用整数算术计算第n次幂的代码来替换 int(pow(...,p))。但是,这似乎有点过分。

If you're really concerned about performance (which I suspect you are not in this case), you can replace int( pow( ..., p ) ) with code that computes the nth power entirely with integer arithmetic. That seems like overkill, though.

这篇关于查找间隔内所有数字的第n个根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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