Answers for "gcd and lcm of two numbers in java"

2

gcd of two numbers in java

// gcd of two numbers in java
import java.util.Scanner;
public class GCDOfTwoNumbers 
{
   public static void main(String[] args) 
   {
      int a, b;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter first number: ");
      a = sc.nextInt();
      System.out.print("Please enter second number: ");
      b = sc.nextInt();
      while(a != b) 
      {
         if(a > b)
         {
            a = a - b;
         }
         else
         {
            b = b - a;
         }
      }
      System.out.println("GCD of two numbers in java: " + b);
      sc.close();
   }
}
Posted by: Guest on February-22-2021
1

Java program to find LCM of two numbers

calculate lcm two numbers in java we can use GCD
public class LCMUsingGCD 
{
   public static void main(String[] args) 
   {
      int num1 = 15, num2 = 25, gcd = 1;
      for(int a = 1; a <= num1 && a <= num2; ++a)
      {
         if(num1 % a == 0 && num2 % a == 0)
         {
            gcd = a;
         }
      }
      int lcm = (num1 * num2) / gcd;
      System.out.println("LCM of " + num1 + " and " + num2 + " is " + lcm + ".");
   }
}
Posted by: Guest on October-30-2020

Code answers related to "gcd and lcm of two numbers in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language