2012年10月24日 星期三

[cpp] GCD Recursion Example


[cpp] GCD Recursion Example

#include <iostream> 
using namespace std; 

int GCD(int, int); 

int main() { 
    int m = 15;
    int n = 45; 

    cout << "GCD: "
         
         << GCD(m, n) << endl; 

    return 0; 
} 

int GCD(int m, int n) {

    cout << "01  GCD(" << m << ", " << n << ");" << endl;  
    
    if(n == 0) 
        return m; 
    else
        cout << "02  GCD(" << n << ", " << m%n << ");" << endl;
        return GCD(n, m % n);

}


Output:
1
2
3
4
5
6
01  GCD(15, 45);
02  GCD(45, 15);
01  GCD(45, 15);
02  GCD(15, 0);
01  GCD(15, 0);
GCD: 15

沒有留言:

張貼留言