81 lines
2.0 KiB
C++
81 lines
2.0 KiB
C++
/*
|
|
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 <iostream>
|
|
#include <exception>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
|
|
/*
|
|
* 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("<<int_A << ") I=" << i << std::endl;
|
|
long long test = 1;
|
|
for ( int j = 0; j < i; ++j ) {
|
|
test *= int_A;
|
|
}
|
|
if ( test == X ) {
|
|
std::cout << "X=" << X << " A=" << int_A << " I=" << i << std::endl;
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
std::cout << "X=" << X << " no power found." << std::endl;
|
|
return false;
|
|
}
|
|
|
|
|
|
int main ( void )
|
|
{try{
|
|
auto begin = std::chrono::high_resolution_clock::now();
|
|
|
|
isPower(1);
|
|
isPower(4);
|
|
isPower(3);
|
|
isPower(27);
|
|
isPower(1024000000);
|
|
isPower(1024*1024*1024);
|
|
|
|
//......
|
|
|
|
auto end = std::chrono::high_resolution_clock::now();
|
|
std::chrono::duration<double> 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;
|
|
}}
|
|
|