aboutsummaryrefslogtreecommitdiff
path: root/challenge-169/ulrich-rieke/cpp/ch-2.cpp
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2022-06-14 21:44:13 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2022-06-14 21:44:13 +0100
commit3a6c5bb04db16be0d61eeac0d74488966d6ba2f4 (patch)
treeec3fe8f262e9806823ec1f6b280e00f40921b0d9 /challenge-169/ulrich-rieke/cpp/ch-2.cpp
parent9f829447426710a7e62cf875f8c3c7a03d256dfd (diff)
downloadperlweeklychallenge-club-3a6c5bb04db16be0d61eeac0d74488966d6ba2f4.tar.gz
perlweeklychallenge-club-3a6c5bb04db16be0d61eeac0d74488966d6ba2f4.tar.bz2
perlweeklychallenge-club-3a6c5bb04db16be0d61eeac0d74488966d6ba2f4.zip
- Added solutions by Ulrich Rieke.
Diffstat (limited to 'challenge-169/ulrich-rieke/cpp/ch-2.cpp')
-rw-r--r--challenge-169/ulrich-rieke/cpp/ch-2.cpp66
1 files changed, 66 insertions, 0 deletions
diff --git a/challenge-169/ulrich-rieke/cpp/ch-2.cpp b/challenge-169/ulrich-rieke/cpp/ch-2.cpp
new file mode 100644
index 0000000000..ffbcfcdd34
--- /dev/null
+++ b/challenge-169/ulrich-rieke/cpp/ch-2.cpp
@@ -0,0 +1,66 @@
+#include <iostream>
+#include <algorithm>
+#include <map>
+#include <vector>
+#include <numeric>
+#include <iterator>
+
+std::vector<int> primeDecompose( int n ) {
+ std::vector<int> primeFactors ;
+ int current = 2 ;
+ while ( n != 1 ) {
+ if ( n % current == 0 ) {
+ primeFactors.push_back( current ) ;
+ n /= current ;
+ }
+ else {
+ current++ ;
+ }
+ }
+ return primeFactors ;
+}
+
+int my_gcd( int a , int b ) {
+ std::vector<int> firstFactors( primeDecompose( a ) ) ;
+ std::vector<int> secondFactors( primeDecompose( b ) ) ;
+ std::vector<int> common ;
+ std::set_intersection( firstFactors.begin( ) , firstFactors.end( ) ,
+ secondFactors.begin( ) , secondFactors.end( ) ,
+ std::inserter( common, common.begin( ) )) ;
+ return std::accumulate( common.begin( ) , common.end( ) , 1 ,
+ std::multiplies( ) ) ;
+}
+
+bool isAchilles( int n ) {
+ std::vector<int> primeFactors( primeDecompose( n ) ) ;
+ std::map<int , int> factorCount ;
+ for ( int i : primeFactors ) {
+ factorCount[ i ]++ ;
+ }
+ std::vector<int> exponents ;
+ for ( auto it = factorCount.begin( ) ; it != factorCount.end( ) ; ++it ) {
+ exponents.push_back( it->second ) ;
+ }
+ if ( *std::min_element(exponents.begin( ) , exponents.end( ) ) >= 2 ) {
+ int start = *exponents.begin( ) ;
+ return (std::accumulate( exponents.begin( ) , exponents.end( ) , start ,
+ []( int a , int b ){ return my_gcd( a , b ) ; } ) == 1 ) ;
+ }
+ else
+ return false ;
+}
+
+int main( ) {
+ std::vector<int> achillesNumbers ;
+ int current = 2 ;
+ while ( achillesNumbers.size( ) != 20 ) {
+ if ( isAchilles( current ) ) {
+ achillesNumbers.push_back( current ) ;
+ }
+ current++ ;
+ }
+ for ( int i : achillesNumbers )
+ std::cout << i << " " ;
+ std::cout << std::endl ;
+ return 0 ;
+}