From 6ebffe2b0337bed8105897fc00e20781194e08d7 Mon Sep 17 00:00:00 2001 From: Mohammad S Anwar Date: Sun, 30 Jan 2022 04:09:52 +0000 Subject: - Added solutions by Ulrich Rieke. --- challenge-149/ulrich-rieke/cpp/ch-2.cpp | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 challenge-149/ulrich-rieke/cpp/ch-2.cpp (limited to 'challenge-149/ulrich-rieke/cpp/ch-2.cpp') diff --git a/challenge-149/ulrich-rieke/cpp/ch-2.cpp b/challenge-149/ulrich-rieke/cpp/ch-2.cpp new file mode 100644 index 0000000000..abc278d886 --- /dev/null +++ b/challenge-149/ulrich-rieke/cpp/ch-2.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include +#include + +long parseBase( std::string numberstring , int base ) { + static std::string allBases {"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"} ; + long base10 = 0 ; + long current = 1 ; + auto start { allBases.begin( ) } ; + std::reverse( numberstring.begin( ) , numberstring.end( ) ) ; + for ( auto c : numberstring ) { + auto found = std::find( allBases.begin( ) , allBases.end( ) , c ) ; + long steps = static_cast( std::distance(start , found )) ; + base10 += steps * current ; + current *= base ; + } + return base10 ; +} + +bool isPerfectSquare( long number ) { + long double root = sqrtl( static_cast( number ) ) ; + return ( floorl( root ) == root ) ; +} + + +int main( int argc, char * argv[0] ) { + int n = std::atoi( argv[1] ) ; + std::string allBases {"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"} ; + std::string selection { allBases.substr( 0 , n ) } ; + reverse( selection.begin( ) , selection.end( ) ) ; + bool found = false ; + do { + long theNumber = 0 ; + if ( n == 10 ) + theNumber = std::stoul( selection ) ; + else + theNumber = parseBase( selection , n ) ; + if ( isPerfectSquare( theNumber ) ) { + std::cout << selection << std::endl ; + found = true ; + break ; + } + } while ( std::prev_permutation( selection.begin( ) , selection.end( ) )) ; + if ( found == false ) + std::cout << "no perfect square in base " << n << " was found!\n" ; + return 0 ; +} -- cgit