71.3k views
0 votes
Write a code that calculates the Greatest Common Divisor (GCD) of two positive integers (user-defined inputs). Include an exception such that if their greatest common divisor equals to 1, it prints out the message, saying its GCD is 1.

User Polarblau
by
5.6k points

1 Answer

4 votes

Answer:

This program is written using Java programming language

import java.util.*;

public class calcGcd

{

public static void main (String [] args)

{

int num1, num2;

Scanner input = new Scanner(System.in);

//Input two integers

num1 = input.nextInt();

num2 = input.nextInt();

//Get least of the two integers

int least = num1;

if(num1 > num2)

{

least = num2;

}

//Initialize gcd to 1

int gcd = 1;

//Calculate gcd using for loop

for(int i=1;i<=least;i++)

{

if(num1%i == 0 && num2%i == 0)

{

gcd = i;

}

}

if(gcd == 1)

{

System.out.print("GCD is 1");

}

else

{

System.out.print("GCD is "+gcd);

}

}

}

Step-by-step explanation:

To calculate the GCD, the program uses a for loop that iterates from 1 to the smaller number of the user input.

Within this iteration, the program checks for a common divisor of the two user inputs by the iterating element

The GCD is then displayed afterwards;

However, if the GCD is 1; the program prints the message "GCD is 1"

Line by Line Explanation

This line declares two integer numbers

int num1, num2;

This line allows user the program to accept user defined inputs

Scanner input = new Scanner(System.in);

The next two line allows gets inputs from the user

num1 = input.nextInt();

num2 = input.nextInt();

To calculate the GCD, the smaller of the two numbers is needed. The smaller number is derived using the following if statement

int least = num1;

if(num1 > num2)

{

least = num2;

}

The next line initializes GCD to 1

int gcd = 1;

The GCD is calculated using the following for loop

The GCD is the highest number that can divide both numbers

for(int i=1;i<=least;i++)

{

if(num1%i == 0 && num2%i == 0)

{

gcd = i;

}

}

The following is printed if the calculated GCD is 1

if(gcd == 1)

{

System.out.print("GCD is 1");

}

Otherwise, the following is printed

else

{

System.out.print("GCD is "+gcd);

}

User Ophir Bushinsky
by
5.6k points