diff --git a/puzzles/interviews/training/power_ap.cpp b/puzzles/interviews/training/power_ap.cpp new file mode 100644 index 0000000..d510845 --- /dev/null +++ b/puzzles/interviews/training/power_ap.cpp @@ -0,0 +1,80 @@ +/* +VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I." +VIM: let b:wcppflags="/O2 /EHsc /DWIN32" +VIM-: let b:cppflags=g:Iboost.g:Itbb +VIM-: let b:ldflags=g:Lboost.g:Ltbb +VIM-: let b:ldlibpath=g:Bboost.g:Btbb +VIM-: let b:argv="" +*/ +#include +#include +#include +#include + +/* + * Given a positive integer which fits in a 32 bit signed integer, find if it + * can be expressed as A^P where P > 1 and A > 0. A and P both should be + * integers. + */ + +bool isPower(int X) { + + if ( X == 1 ){ + return true; + } + + double log_X = std::log(X); + long long end = log_X / std::log(2) +1; + for ( int i = 2; i <= end; ++i ) { + double A = std::exp(log_X/double(i)); + double rA = std::round(A); + std::cout << "--> A=" << A << " r(" << rA << ") I=" << i << " diff=" << std::fabs(A-rA) << std::endl; + if ( std::fabs(A-rA) < 0.00001 ) { + int int_A = rA; + std::cout << "Testing --> A=" << A << " r("< seconds = end - begin; + std::cout << "Time: " << seconds.count() << std::endl; + return 0; +} +catch ( const std::exception& e ) +{ + std::cerr << std::endl + << "std::exception(\"" << e.what() << "\")." << std::endl; + return 2; +} +catch ( ... ) +{ + std::cerr << std::endl + << "unknown exception." << std::endl; + return 1; +}} +