Friday 15 August 2014

c++ - Determining the largest value before hitting infinity -



c++ - Determining the largest value before hitting infinity -

i have simple function checks value of (n^n-1)^(n-2):

int main() { // declare variables double n; double answer; // function cout << "please come in double number >= 3: "; cin >> n; reply = pow(n,(n-1)*(n-2)); cout << "n n-1) n-2 doubles " << reply << endl; }

based on formula, evident reach infinity, curious until number/value of n nail infinity? using loop seems extremely inefficient, that's can think of. basically, creating loop says allow n number between 1 - 100, iterate until n == inf

is there more efficient approach problem?

two things: first (n^(n-1))^(n-2)) can written n^((n-1)*(n-2)). remove 1 pow phone call making code faster.

pow(n, (n-1)*(n-2));

the sec know practical limits hit, testing n literally take fraction of second, there no reason find practical way.

you compute hand knowing variable size limits , all, testing faster. illustration code (c++11, since utilize 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; } homecoming 0; }

this illustration takes less millisecond on computer, , prints 17.28894235

c++

No comments:

Post a Comment