Question: Java Question The starter code is given as : import java.util.Scanner; public class RecursiveMultiply { public static void main(String[] args) { Scanner scan = new

Java Question

Java Question The starter code is given as : import java.util.Scanner; public

The starter code is given as :

import java.util.Scanner; public class RecursiveMultiply { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int x = scan.nextInt(); int y = scan.nextInt(); long start = System.currentTimeMillis(); long z = mult(x,y); long t = System.currentTimeMillis() - start; System.out.println(z); // Use the following if you want to find run time. //System.out.println("Elapsed time = " + t); } public static long mult(int a, int b) { return (long) a*b; } }

For the recursive method, I currently have:

if (a==1){

return b;}

if (a%2==1){

return (long) mult(a, b-1)+a;

}

else{

return (long) (mult(a, (b-1)/2)+a)+ (mult(a, (b-1)/2)+a);

}

I tested other codes and it failed the test for 20000000 20000000 becuase it wasnt efficient enough so I figured if I add a part for when a is negative and positive it would pass the efficiency test but I am having trouble implementing that.

Any help would be greatly appreciated.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!