#include #include #include using namespace std ; /***************************************************************************** print the gcd procedure 1 | 1 2 0 | 7 8 | 1 | 7 8 | 4 2 | | ------------ | ------------ | 1 | 4 2 | 3 6 | 6 | 3 6 | 3 6 | | ------------ | ------------ | | 6 | 0 | ==> GCD = 6 *****************************************************************************/ // 對調兩整數 void swap( int& a , int& b ) { int c = a ; a = b ; b = c ; } // 取出整數 no 的第 n 位數 inline int nth_digit( int no , int n ) { for ( int i = 1 ; i < n ; ++i ) no /= 10 ; return ( no % 10 ) ; } // 計算整數 no 的位數 inline int digits_no( int no ) { int i ; for ( i = 0 ; no != 0 ; ++i ) no /= 10 ; return i ; } // 整數轉字串, 且在數字之間加上空格 string convert_string( int number ) { if ( number == 0 ) return string(" 0") ; string space = " " ; string no ; int na = digits_no(number) ; for ( int i = na ; i >= 1 ; --i ) { no += space + static_cast('0'+nth_digit(number,i)) ; } return no ; } // 列印計算 gcd 過程 void print_gcd( int x1 , int x2 ) { int x3 = x1 ; int a1 , a2 , c1 , c2 , e1 , e2 , gcd ; string line(12,'-') ; if ( x1 < x2 ) swap( x1 , x2 ) ; cout << endl ; while ( x1 * x2 != 0 ) { a1 = x1/x2 ; c1 = a1*x2 ; e1 = x1%x2 ; if ( e1 == 0 ) { gcd = x2 ; } else { a2 = x2/e1 ; c2 = a2*e1 ; e2 = x2%e1 ; if ( e2 == 0 ) gcd = e1 ; } cout << setw(2*6) << convert_string(a1) << " | " << setw(2*6) << convert_string(x1) << " | " << setw(2*6) << convert_string(x2) << " | " ; if ( e1 != 0 ) cout << convert_string(a2) ; cout << endl ; cout << setw(2*6) << " " << " | " << setw(2*6) << convert_string(c1) << " | " ; if ( e1 != 0 ) cout << setw(2*6) << convert_string(c2) ; else cout << setw(2*6) << " " ; cout << " |\n" << setw(2*6) << " " << " | " << setw(2*6) << line << " | " ; if ( e1 == 0 ) cout << setw(2*6) << " " << " |\n" ; else cout << setw(2*6) << line << " |\n" ; x1 = e1 ; x2 = e2 ; if ( e1 == 0 ) { cout << setw(2*6) << " " << " | " << setw(2*6) << 0 << " | " << setw(2*6) << " " << " | " << endl ; } else if ( e2 == 0 ) { cout << setw(2*6) << " " << " | " << setw(2*6) << convert_string(x1) << " | " << setw(2*6) << 0 << " | " << endl ; } } cout << "\n==> GCD = " << gcd << "\n\n" ; } int main() { int a , b ; while (1) { cout << "> input two numbers : " ; cin >> a >> b ; print_gcd(a,b) ; } return 0 ; }