m2skills

lcm java

Jul 26th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. // Program to find LCM of 2 given numbers
  2.  
  3. import java.util.Scanner;
  4. import java.io.*;
  5.  
  6. public class lcm{
  7.     public static void main(String arg[]){
  8.         Scanner sc = new Scanner(System.in);
  9.         boolean cont = true;
  10.         while(cont){
  11.        
  12.             System.out.print("\nEnter the first number : ");
  13.             int num1 = sc.nextInt();
  14.             System.out.print("Enter the second number : ");
  15.             int num2 = sc.nextInt();
  16.            
  17.             int res = LCM(num1, num2);
  18.             System.out.println("The LCM of " + num1 + " and " + num2 + " is : " + res);
  19.            
  20.             System.out.print("Do you want to continue (1/0): ");
  21.             int c = sc.nextInt();
  22.             if(c == 0){
  23.                 cont = false;
  24.             }
  25.         }  
  26.     }
  27.    
  28.    
  29.     // method to find gcd of 2 numbers
  30.     static int gcd (int m1 , int m2)
  31.     {
  32.         if(m1==0 || m2==0)
  33.         {
  34.             return 0;
  35.         }
  36.             do
  37.             {
  38.                 if(m1 > m2)
  39.                 {
  40.                     m1 = m1 - m2;
  41.                 }
  42.                 else
  43.                 {
  44.                     m2 = m2 - m1;
  45.                 }
  46.  
  47.             }while(m1!=m2);
  48.  
  49.             return(m1);
  50.     }
  51.  
  52.  
  53.     // method that finds lcm of numbers
  54.     static int LCM(int num1, int num2){
  55.        
  56.         int res = gcd(num1, num2);
  57.         int lcm_num = (num1 * num2) / res;
  58.         return lcm_num;
  59.     }
  60. }
  61.  
  62. /*
  63.  
  64. Enter the first number : 12
  65. Enter the second number : 14
  66. The LCM of 12 and 14 is : 84
  67. Do you want to continue (1/0): 1
  68.  
  69. Enter the first number : 15
  70. Enter the second number : 25
  71. The LCM of 15 and 25 is : 75
  72. Do you want to continue (1/0): 0
  73.  
  74. */
Add Comment
Please, Sign In to add comment