我有一个非常简单的函数来检查(N ^ N-1)^(N-2)的值:
int main() {
// Declare Variables
double n;
double answer;
// Function
cout << "Please enter a double number >= 3: ";
cin >> n;
answer = pow(n,(n-1)*(n-2));
cout << "n to the n-1) to the n-2 for doubles is " << answer << endl;
}
根据这个公式,很明显它将达到无穷大,但是我很好奇直到n的多少个数值/值会达到无穷大?使用循环似乎效率极低,但这就是我能想到的。基本上,创建一个循环,让n为1-100之间的数字,迭代直到n == inf
有没有更有效的方法来解决这个问题?
有两件事:第一是(N ^(N-1))^(N-2))可以写成N ^((N-1)*(N-2))。因此,这将消除一次pow
调用,从而使您的代码更快。
pow(n, (n-1)*(n-2));
第二个是要知道您遇到了什么实际的限制,测试所有N会花费一秒钟的时间,因此实际上没有理由找到另一种实际的方法。
您可以手动了解变量大小限制以及所有限制,但是绝对可以更快地进行测试。代码示例(C ++ 11,因为我使用std::isinf
):
#include <iostream>
#include <cmath>
#include <iomanip>
int main() {
double N = 1.0, diff = 10.0;
const unsigned digits = 10;
unsigned counter = digits;
while ( true ) {
double X = std::pow( N, (N-1.0) * (N-2.0) );
if ( std::isinf(X) ) {
--counter;
if ( !counter ) {
std::cout << std::setprecision(digits) << N << "\n";
break;
}
N -= diff;
diff /= 10;
}
N += diff;
}
return 0;
}
此示例在我的计算机上花费不到一毫秒的时间,并且可以打印 17.28894235
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句