Provides to you, the basics of Java and its programs, which are of the ICSE standard in India, as well as the facility to ask questions and get the programs done in no time. Useful for home works. Just copy, paste and compile the programs. Contact us at icse.java.blogspot@gmail.com

Thursday, 4 August 2011

To find the LCM of two numbers

Question 37 : Write a program in Java to find the Lowest Common Multiple (L.C.D.) of two numbers entered by the user :

import java.io.*;class LcmMethod_2{public static void main()throws IOException{BufferedReader br=new BufferedReader(new InputStreamReader(System.in));int a,b,max,min,x,lcm=1;System.out.print("Enter the 1st number : ");a=Integer.parseInt(br.readLine());System.out.print("Enter the 2nd number : ");b=Integer.parseInt(br.readLine());if(a>b){max=a;min=b;}else{max=b;min=a;}/*To find the maximum and minimum numbers, you can also useint max=a>b?a:b;int min=a<b?a:b;*/for(int i=1;i<=min;i++){x=max*i; //finding multiples of the maximum numberif(x%min==0) //Finding the multiple of maximum number which is divisible by the minimum number.{lcm=x; //making the first multiple of maximum number which is divisible by the minimum number, as the LCMbreak; //exiting from the loop, as we don’t need anymore checking after getting the LCM}}System.out.println("L.C.M. = "+lcm);}}