Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iterator>
- #include <vector>
- using std::size, // From <iterator>
- std::vector; // From <vector>
- template< class Collection >
- auto int_size( const Collection& c )
- -> int
- { return static_cast<int>( size( c ) ); }
- auto is_even( const int v )
- -> bool
- { return v % 2 == 0; }
- auto next_collatz( const int v )
- -> int
- { return is_even( v )? v/2 : 3*v + 1; }
- auto collatz( const int n )
- -> vector<int>
- {
- vector<int> result;
- for( int x = n; x != 1; x = next_collatz( x ) ) {
- result.push_back( x );
- }
- result.push_back( 1 );
- return result;
- }
- #include <iostream>
- using std::cout, std::endl; // From <iostream>
- auto main() -> int
- {
- const int n = 42;
- const vector<int> numbers = collatz( n );
- cout << "Collatz sequence starting with " << n << ", one per line:" << endl;
- cout << endl;
- for( const int v: numbers ) {
- cout << "> " << v << endl;
- }
- cout << endl;
- cout << "The same numbers but with all on one line:" << endl;
- cout << endl;
- cout << "> ";
- for( int i = 0; i < int_size( numbers ); ++i ) {
- if( i > 0 ) {
- cout << ", ";
- }
- cout << numbers[i];
- }
- cout << "." << endl;
- }
Add Comment
Please, Sign In to add comment