// Iterates the function 'sumsquaredigits' until it reaches state N=1 #include using namespace std; // This function assumes positive n int sumsquaredigits (int n) { int answer = 0 , rem ; while ( n > 0 ) { rem = n%10 ; // the remainder is the next digit (Reading from the right) answer += rem * rem ; n = n/10 ; } return answer ; } int main(int argc, char* argv[]) { int N=12; // starting number int I=1000; // maximum number of iterations int match1=1; // termination condition int match2=4; // termination condition if(argc>1) { sscanf( argv[1], "%d", &N ) ; // put the first command-line argument in N } cout << N << endl ; for ( int i = 1 ; i <= I ; i ++ ) { N = sumsquaredigits( N ) ; cout << N << " " ; if ( N == match1 || N == match2 ) { cout << "\n(" << i << " iterations)\n" ; return 0; } if ( !(i%10) ) cout << endl ; } return 0; }