递归(最大公约数)
- 求最大公约数:
1 #include <iostream> 2 using namespace std; 3 // recursive version greatest common divisor program 4 int rgcd(int v1, int v2) 5 { 6 if (v2 != 0) // we're done once v2 gets to zero 7 return rgcd(v2, v1%v2); // recurse, reducing v2 on each call 8 return v1; 9 } 10 int main() 11 { 12 int a = rgcd(128,64); 13 cout << a <<endl; 14 return 0; 15 }
如
f(29,3)->f(3,2)->f(2,1)->f(1,0)->return 1
f(96,64)->f(64,32)->f(32,0)->return 32非递归:
1 #include <iostream> 2 using namespace std; 3 int rgcd(int v1, int v2) 4 { 5 while(v2 != 0) 6 { 7 int t = v1; 8 v1 = v2; 9 v2 = t%v2; 10 } 11 return v1; 12 } 13 int main() 14 { 15 int a = rgcd(96,64); 16 cout << a <<endl; 17 return 0; 18 }