[*]The method must be static with only two int parameters
[*]The method must be recursive, and cannot use any loops
[*]The method can not call any other methods, nor can it call any overloaded methods
The method returns the least common multiple of Аргументы переданы в него < /li>
< /ol>
Мой вопрос: возможно ли это даже без третьего параметра?
Код: Выделить всё
public static int findLCM (int a, int b) {
if (a % b == 0)
return a;
else
return findLCM(a + a, b);
}
However as you can clearly see, this code does not do that, because the statement
return findLCM(a + a, b);
< /code>
будет работать только с параметром Thrid, а затем переписывается как < /p>
return findLCM(a + originalA, b);
< /code>
Я не могу найти каким -либо образом, что это было бы возможно, не добавляя 3 -й параметр.// Doesn't work. Attempts to get greatest common denominator first, then apply the formula to find the LCM at the first instance of the method being called
// but there seems to be no way to really detect when to apply this final formula
public static int findLCM (int a, int b) {
int result;
if (b == 0)
return a;
else {
result = findLCM(b, a % b);
// When to return gcd, or return lcm???
if (result == b)
return result;
else
return (a * b) / result; // formula for lcm
}
}
< /code>
Я подумал о том, чтобы попробовать первичную факторизацию, а затем использовать ее, чтобы найти LCM, но я уверен, что у него будет та же проблема, что и получение GCD, а затем поиск LCM. Это просто невозможно без других методов или петель. На самом деле есть способ рекурсивно найти LCM только с двумя параметрами, а также без петли или других вызовов метода. Или я намазал свой мозг за что -то? Это простой класс Java, я чувствую, что это действительно не должно быть так сложно. Либо задание невозможно, либо я упускаю что -то очевидное ... < /p>
Спасибо за любую помощь < /p>
Подробнее здесь: https://stackoverflow.com/questions/273 ... in-a-recur