GCD of 2 Numbers

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 36:- GCD of 2 Numbers

To calculate the Greatest Common Divisor (GCD) of two numbers in Java, you can use the Euclidean algorithm. The GCD of two integers is the largest positive integer that divides both of them without leaving a remainder. Here's a Java program to calculate the GCD of two given numbers:

javaCopy code
import java.util.Scanner; public class GCDCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Calculate the GCD using the Euclidean algorithm int gcd = calculateGCD(num1, num2); System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd); scanner.close(); } // Function to calculate GCD using the Euclidean algorithm public static int calculateGCD(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } }

Example output:

mathematicaCopy code
Enter the first number: 24 Enter the second number: 18 GCD of 24 and 18 is: 6

In the program above, we take the user input for the two numbers and store them in num1 and num2 variables. We then call the calculateGCD function to calculate the GCD using the Euclidean algorithm. The calculateGCD function uses a while loop to repeatedly find the remainder of a divided by b and swap the values of a and b until b becomes zero. At that point, the value of a will be the GCD.

The calculateGCD function is a separate method to demonstrate how to calculate the GCD using a function. It allows you to reuse the code in different parts of the program if needed.

The program then prints the GCD of the two numbers to the console.

 

Disclaimer:-

Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.

 

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?