Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

USING JAVA: -For this assignment we are going to take another look at Greatest Common Divisor(GCD) of two numbers. You will have it calculated recursively

USING JAVA:

-For this assignment we are going to take another look at Greatest Common Divisor(GCD) of two numbers. You will have it calculated recursively instead of iteratively.

-You will be "filling in" the portion of existing code to calculate recursively the GCD.

For coding the file follow this:

Fill in the body of the recGCD() methods with code that implements a similar algorithm.

Here is the algorithm you should use:

Take two numbers x and y

Divide x by y and get the remainder

if the remainder equals 0, GCD is y (end the function)

otherwise, calculate GCD again by dividing y by the remainder (this is the swap part that we did in the original iterative GCD)

image text in transcribed

THE EXISTING CODE:

import java.util.Scanner; public class GCDApp { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first number: "); int firstNumber = Integer.parseInt(sc.nextLine()); System.out.print("Enter the second number: "); int secondNumber = Integer.parseInt(sc.nextLine()); System.out.println("Iterative GCD..."); int result = iterGCD(firstNumber, secondNumber); System.out.println(result); System.out.println("Recursive GCD..."); result = recGCD(firstNumber, secondNumber); System.out.println(result); System.out.println(); } // iterative public static int iterGCD(int a, int b) { System.out.println("Iterative solution here..."); int remainder = a % b; // initial division while (remainder != 0) // checks if remainder is 0, once it is we have our GCD { a = b; // overwrite a with b b = remainder; // overwrite b with remainder remainder = a % b; // perform division again to check GCD } return b; } // recursive public static int recGCD(int a, int b) { System.out.println("Recursive solution here..."); return 0; } }
Here is the screenshot of the solution run. Enter the first number: 63 Enter the second number: 21 Iterative GCD... 21 Recursive GCD... Recursive call 21

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

Recommended Textbook for

Modern Database Management

Authors: Jeff Hoffer, Ramesh Venkataraman, Heikki Topi

12th edition

133544613, 978-0133544619

More Books

Students also viewed these Databases questions

Question

Determine the amplitude and period of each function.

Answered: 1 week ago