Calculating the GCD of two numbers in Java

Problem:

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write an application that reads two integers from the user and then prints their greatest common divisor. Implement this exercise using Functions.

Output:

Not needed.

Solution:

import java.util.Scanner;
public class problem4 
{
 public static void main(String[] args)
 {
  Scanner scan=new Scanner(System.in);
  int GCD=0,smallest;
  System.out.println("Enter the two numbers:");
  int num1=scan.nextInt();
  int num2=scan.nextInt();
  if(num1<num2)
   smallest=num1;
   
  else
   smallest=num2;
  
  for(int n=smallest;n>=1;n--)
  {
   if((num1%n==0) && (num2%n==0))
   {
    GCD=n;
    n=0;//to exit loop
   }
  }

  System.out.println("The GCD is: "+ GCD);
 }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact