diff options
| author | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2022-07-27 21:12:45 +0100 |
|---|---|---|
| committer | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2022-07-27 21:12:45 +0100 |
| commit | d2a093191440c0932086eac5f42db7541ccbd6d7 (patch) | |
| tree | baace5a9fc75291046295413177cd098c2e7a3ec /challenge-175/ulrich-rieke/cpp/ch-2.cpp | |
| parent | 4fcc4e6faca6301608b3777f959573cb0edddffb (diff) | |
| download | perlweeklychallenge-club-d2a093191440c0932086eac5f42db7541ccbd6d7.tar.gz perlweeklychallenge-club-d2a093191440c0932086eac5f42db7541ccbd6d7.tar.bz2 perlweeklychallenge-club-d2a093191440c0932086eac5f42db7541ccbd6d7.zip | |
- Added solutions by Ulrich Rieke.
Diffstat (limited to 'challenge-175/ulrich-rieke/cpp/ch-2.cpp')
| -rw-r--r-- | challenge-175/ulrich-rieke/cpp/ch-2.cpp | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/challenge-175/ulrich-rieke/cpp/ch-2.cpp b/challenge-175/ulrich-rieke/cpp/ch-2.cpp new file mode 100644 index 0000000000..2f910a3bfc --- /dev/null +++ b/challenge-175/ulrich-rieke/cpp/ch-2.cpp @@ -0,0 +1,55 @@ +#include <iostream> +#include <vector> +#include <numeric> +#include <algorithm> + +int my_gcd( int a , int b ) { //Euclid's algorithm + if ( b >= a ) + std::swap( a , b ) ; + while ( a != b ) { + a = a - b ; + if ( b >= a ) + std::swap( a , b ) ; + } + return a ; +} + +int myPhi( int n ) { + std::vector<int> totatives ; + for ( int i = 1 ; i < n ; i++ ) { + if ( my_gcd( i , n ) == 1 ) + totatives.push_back( i ) ; + } + return totatives.size( ) ; +} + +bool isPerfectTotient( int n ) { + if ( n == 1 ) { + return false ; + } + int current = n ; + std::vector<int> totients ; + do { + current = myPhi( current ) ; + totients.push_back( current ) ; + } while ( current != 1 ) ; + return std::accumulate( totients.begin( ) , totients.end( ) , 0 ) == n ; +} + +int main( ) { + std::vector<int> perfectTotients ; + int current = 1 ; + while ( perfectTotients.size( ) != 20 ) { + if ( isPerfectTotient( current ) ) { + perfectTotients.push_back( current ) ; + } + current++ ; + } + for ( int i : perfectTotients ) { + std::cout << i ; + if ( i != perfectTotients.back( ) ) + std::cout << ',' ; + } + std::cout << std::endl ; + return 0 ; +} |
