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

Spring 2012 Problem 3 (45%) Write a program that calculate the greatest common d

ID: 3639037 • Letter: S

Question

Spring 2012 Problem 3 (45%) Write a program that calculate the greatest common divisor of two positive integers Nt and N2. The greatest common divisor can be calculated by iteratively replacing the larger of the two numbers by the difference of numbers until the smaller of the two numbers reaches zero. When the smallest number becomes zero, the other gives the greatest common divisor. Requirements: Enter N1 and N2 using input statements. Enter first number: Enter second number: Output should be as follows: The greastest common divisor of and is

Explanation / Answer

// Calculating the GCD of two integers import java.util.Scanner; public class GreatestCommonDivisor { public static void main(String[] args) { int number1, number2; //two number for GCD calculation. //create a scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); boolean choice = true;//for repetition of calculation while(choice) { //get the numbers from the user System.out.print("Enter first number: "); number1 = keyboard.nextInt(); System.out.print("Enter second number: "); number2 = keyboard.nextInt(); //call the GCD method for calculate the GCD of given two numbers. int gcd = calculateGCD(number1, number2); //display the GCD of two numbers. System.out.println("The greatest common divisor of "+number1+" and "+number2+" is "+gcd); System.out.print("Do you want to calculate GCD of another two integers? choose y or Y for continue."); String s = keyboard.next(); if(!s.equalsIgnoreCase("y")) { choice = false; System.out.println("Thank you."); } }//end of while loop }//end of main method public static int calculateGCD(int n1, int n2) { int difference; if(n1 == n2) { return n1; // or you can return n2 } else if(n1
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote