aboutsummaryrefslogtreecommitdiff
path: root/challenge-149/ulrich-rieke/cpp/ch-2.cpp
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2022-01-30 04:09:52 +0000
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2022-01-30 04:09:52 +0000
commit6ebffe2b0337bed8105897fc00e20781194e08d7 (patch)
tree93225f45689f4f58410b9cf48474d0a2ee08a595 /challenge-149/ulrich-rieke/cpp/ch-2.cpp
parent55bf45bd448354184f196a5c04404b3ff8c7db64 (diff)
downloadperlweeklychallenge-club-6ebffe2b0337bed8105897fc00e20781194e08d7.tar.gz
perlweeklychallenge-club-6ebffe2b0337bed8105897fc00e20781194e08d7.tar.bz2
perlweeklychallenge-club-6ebffe2b0337bed8105897fc00e20781194e08d7.zip
- Added solutions by Ulrich Rieke.
Diffstat (limited to 'challenge-149/ulrich-rieke/cpp/ch-2.cpp')
-rw-r--r--challenge-149/ulrich-rieke/cpp/ch-2.cpp50
1 files changed, 50 insertions, 0 deletions
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 <iostream>
+#include <string>
+#include <algorithm>
+#include <cstdlib>
+#include <cmath>
+#include <iterator>
+
+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<long>( std::distance(start , found )) ;
+ base10 += steps * current ;
+ current *= base ;
+ }
+ return base10 ;
+}
+
+bool isPerfectSquare( long number ) {
+ long double root = sqrtl( static_cast<long double>( 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 ;
+}