Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Multiplying two integers, a and b, is actually done by adding the first number,

ID: 3707395 • Letter: M

Question

Multiplying two integers, a and b, is actually done by adding the first number, a, to itself b times. Dividing two numbers, a and b, is likewise actually done by subtracting the first number, a, from the second number, b, repeatedly until b is smaller than a (this is the remainder). The number of subtractions done is the number of times b goes into a. Write a recursive method that will multiply two numbers by adding the first to itself this way. Write a second recursive method that will divide two numbers this way. Write two non-recursive methods using loops to do the same operations. Using Java Mission Control, run your application with large sets of data using the recursive methods and the iterative methods. You can do this in a for loop that runs dozens or hundreds of times, and generate two random numbers in the loop and call your recursive and your iterative methods with those two random numbers. Look at the sample code that runs recursive and iterative binary search. What does Mission Control tell you about the runtime performance difference between recursive methods and non-recursive methods? Submit your code, and a written report discussing and detailing the difference and the data (along with screenshots of mission control). Partial Pseudo-code: In main Create a loop so you can call your recursive and iterative methods lots of times and get a better picture of the performance difference. Get two random positive numbers Call recursive multiply or divide with them Call iterative multiply or divide (make sure it is the same method as above) with them In multiply (recursive) if b is not 0 add a to result subtract 1 from b return multiply with new parameters else return result In divide (recursive) If b is greater than a subtract b from a, add one to result return divide with new parameters else return result

Explanation / Answer

int mulRecursive(int a , int b)
{

    if(b==0)
    return 0;

    else
    return a+mulRecursive(a,b-1);
}
int divRecursive(int a, int b)
{
    if(a<b)
    {
        return 0;
    }
    else
    {
        return 1+ divRecursive(a-b,b);
    }

}
int mulIterative(int a , int b)
{
    int res=0;
    for(int i=1;i<=b;i++)
    {
        res+=a;
    }
    return res;
}
int divIterative(int a,int b)
{
    int quo=0;
    while(a>=b)
    {
      a-=b;
      quo++;
    }
    return quo;
}