假设有一个方法int Multiply(int x,int y)
。这个方法是否有可能在不使用循环的情况下返回x和y之间所有整数的乘积。
例如,如果使用3和5调用该方法:Multiply(3,5)
则应该返回产品:3*4*5 = 60
。
答案 0 :(得分:4)
有趣的问题。请在下面找到我尝试解决此问题的方法,假设为x is less than or equal to y
public static int multiply(int x, int y){
if(x==y){
return x;
}
if(x == y-1){
return x*y;
}
int product = x*y;
product = product*multiply(x+1,y-1);
return product;
}
答案 1 :(得分:1)
使用Java 8的流:
public static int foo (int x, int y){
int high = x > y ? x : y;
int low = x > y ? y : x;
return IntStream.rangeClosed(low, high).reduce(1, Math::multiplyExact);
}
从技术上讲,没有循环:)