简体   繁体   中英

Need some help interpreting this recursion code

I am new to recursion and my teacher gave us this code to examine:

public long rudolph(long a, long b){
 if(b==0)
   return a;
 else 
   return rudolph(b, a % b);
}

I tried to follow the logic by using different values for a and b each time but I can't make sense of the outcomes. How to figure this out without running it? Basically trying to figure out what this code does in general.

example:

if a = 9 and b = 7:
return rudolph(7,2);
return rudolph(2,1);
return rudolph(1,0);
return 1

if a = 10 and b = 5:
return rudolph(5,0);
return 5

if a = 5 and b = 2:
return rudolph(2,1);
return rudolph(1,0);
return 1

Your best bet is to get a piece of paper and a pencil and record values for a and b at every call. Start with small(er) (a=2,b=3 for example) to see where and how the recursion stops and then you can work your way up from there.

EDIT: Show us what you've tried and we can try to point you in the right direction if you really can't figure it out (there's a difference between being lazy and really not understanding).

函数返回最大公约数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM