I can't understand the funz function, how I can think this code?
i have only this idea:
12 is != 0
return is 12+funz(12,10)
then x=12 y=10
10 is != 0
return is 12+10+funz(10,2)
then x=10 y=2
2 is != 0
return is 12+10+2+funz(2, 0)
then x=2 y=0
0 is = 0
return x (26)
t=26
that's right?

 123456789101112131415161718192021222324 #include using namespace std; int funz(int, int); int main() { int a=10, b=12, t; t = funz(a, b); cout << "t = " << t << endl; return 0; } int funz(int x,int y) { if (y!=0){ cout << y+funz(y, x%y) << endl; return (y+funz(y, x%y)); } else return x; }
 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include int funz(int, int); int main() { std::cout << "0. in main\n" ; int a = 10, b = 12 ; const int t = funz(a, b) ; std::cout << "0. back in main: t == " << t << '\n' ; } std::ostream& spaced_cout( int n ) { for( int i = 0 ; i < n*8 ; ++i ) std::cout << ' ' ; return std::cout << n << ". " ; } int funz( int x, int y ) { static int cnt = 0 ; ++cnt ; spaced_cout(cnt) << "enter funz( " << x << ", " << y << " )\n" << std::flush ; if( y!=0 ) { spaced_cout(cnt) << "call funz( " << y << ", " << x << '%' << y << " )\n" ; const int v = funz( y, x%y ) ; spaced_cout(cnt) << "return " << y << " + " << v << " == " << y+v << '\n' ; --cnt ; return y+v ; } else { spaced_cout(cnt) << "return " << x << '\n' ; --cnt ; return x ; } }

 0. in main 1. enter funz( 10, 12 ) 1. call funz( 12, 10%12 ) 2. enter funz( 12, 10 ) 2. call funz( 10, 12%10 ) 3. enter funz( 10, 2 ) 3. call funz( 2, 10%2 ) 4. enter funz( 2, 0 ) 4. return 2 3. return 2 + 2 == 4 2. return 10 + 4 == 14 1. return 12 + 14 == 26 0. back in main: t == 26

http://coliru.stacked-crooked.com/a/0d72817dd81e1afc
Topic archived. No new replies allowed.