Reputation: 33
Suppose there is a method int Multiply(int x,int y)
. Is it possible for this method to return product of all the integers between x and y without using loop.
For example if the method is called with 3 and 5 : Multiply(3,5)
then it should return the product : 3*4*5 = 60
.
Upvotes: 1
Views: 2236
Reputation: 5153
With Java 8's streams:
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);
}
Technically, there are no loops : )
Upvotes: 1
Reputation: 5336
Interesting question. Please find my attempt to solve this below, The assumption is 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;
}
Upvotes: 4