查找间隔内所有数字的第n个根

编程入门 行业动态 更新时间:2024-10-19 10:25:02
本文介绍了查找间隔内所有数字的第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个根

本文发布于:2023-11-30 04:33:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648738.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:间隔   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!