Reputation: 572
This problem MUST be solved using a recursion.
I tried to use the code after the "else" to find the quotient using an int temp that counts how many times it is possible to divide (temp = dividend - divisor).
int r is supposed to be the quotient, but since division() is not an int but an array, I can't apply the recursion. I tried also to insert division() inside result[0], but same thing, the return is an array, not an int.
The result is an array with 2 elements: the quotient and remainder of the division.
I've been practicing recursion but I'm lost in this mix of recursion and arrays
I can probably solve this with a for loop but as I said, MUST use a recursion.
Only the code between else and return should be modified. If this is supposed to be easy, I don't see it.
I've been searching for answers before but the ones I've found use int as return, not array.
This is the code with my failed test (as you can see in Main, the test dividend is 13 and divisor is 3):
public class Main{
/*
* Returns an array with the quotient and remainder of the
* integer division
*
* @param dividend a positive int
* @param divisor a positive int
*/
static int[] division(int dividend, int divisor){
int result[] = {0, dividend};
if ( dividend < divisor ){
return result;
} else{
***int temp = dividend - divisor;
int r = 1 + division(temp , divisor);***
return result;
}
}
public static void main(String[] args){
int result[]=division(13,3);
System.out.println("Quotient: "+ result[0]
+ " Remainder: "+ result[1]);
}
}
Upvotes: 1
Views: 1966
Reputation: 393846
You are failing since you are trying to add an int to an array and assign the result to an int. Instead, you should add 1 to the first position of the array returned by the recursive call and return that array.
static int[] division(int dividend, int divisor){
int result[] = {0, dividend};
if ( dividend < divisor ){
return result;
} else{
result = division(dividend - divisor, divisor);
result[0]++;
return result;
}
}
Upvotes: 5