开发者

I need some help with a Java recursion problems

This is my first problem:

gcd(x,y)
  if (x < y)
    gcd(y,x)
  else
    if (y = 0)
      return x
    else
      return gcd(y, x mod y)

This is my second problem:

public static int Test2(int x, int y) {
  if (x > y) {
    return 10;
  } else {
    return Test2(x-5, y+5) + 5;
  }
}

The question is: What is returned for gcd(84, 21)?

  • a. 84
  • b. 21
  • c. 3 (This is the correct answer)
  • d. 10

X equals 84 and y equals 21. So I run them through the Algorithm class. 84 is not less than 21 so I skip that if statement. 84 is not equal so I skip that statement. I go to retu开发者_运维知识库rn gcd(y, x mod y). I don’t understand what is mod and how do you figure out what it means?

Second problem! Question: What is returned for Test2(18,5)?

  • A. 5
  • B. 10 I choose ten , because x is greater than y and when processed to the if statement. It returns a value of ten. The if statements does run anything but the return statement.
  • C. 15 The answer is 15.
  • D. 20


mod is the modulo function. It's the rest when when you divide two integers. For example,

1 mod 3 = 1
2 mod 3 = 2
3 mod 3 = 0
4 mod 3 = 1
10 mod 4 = 2

10 is the correct answer for the second question, your argument is correct.


The modulo operator returns the remainder of a divison operation. e.g. 3 mod 2 = 1 since 1 is the remainder. % is commonly used as the symbol for mod. In this example 84 mod 21 equals 0 since 21 divides evenly into 84 four times.


x mod y is not valid Java, x % y is and it means modulo; that what if left after an integer division of x by y.

Btw, what do you mean with this is the answer and the answer is 15? Better to think the problem through and explain your own answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜