Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Create a recursive Java method getProduct to compute the product of two positive integers, m and n , using only addition and subtraction. Implement the

Create a recursive Java method getProduct to compute the product of two positive integers, m and n, using only addition and subtraction. Implement the Java code. Test the method by calling it in the main method of the relevant class. Hint: You need subtraction to count down from m or n and addition to do the arithmetic needed to get the right answer. The linearSum method may be helpful.
public class ArraySum {
/** Returns the sum of the first n integers of the given array. */
public static int linearSum(int[] data, int n){
if (n ==0)
return 0;
else
return linearSum(data, n-1)+ data[n-1];
}
/** Returns the sum of subarray data[low] through data[high] inclusive. */
public static int binarySum(int[] data, int low, int high){
if (low > high)// zero elements in subarray
return 0;
else if (low == high)// one element in subarray
return data[low];
else {
int mid =(low + high)/2;
return binarySum(data, low, mid)+ binarySum(data, mid+1, high);
}
}
public static void main(String[] args){
for (int limit =1; limit <100; limit++){
int[] data = new int[limit];
for (int k=0; k < limit; k++)
data[k]= k+1;
int answer = limit *(limit +1)/2;
int linear = linearSum(data, limit);
if (linear != answer)
System.out.println("Problem with linear sum for n="+ limit);
int binary = binarySum(data,0, limit-1);
if (binary != answer)
System.out.println("Problem with binary sum for n="+ limit);
}
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions