A class LCM has been defined to find the Lowest Common Multiple of two integers.
Some of the data members and member functions are given below:
Class name: LCM
Data members/instance variables:
n1: to store an integer number
n2: to store an integer number
large: integer to store the largest from n1, n2
sm: integer to store the smallest from n1, n2
l: to store LCM of two numbers
Methods/Member functions:
LCM(): default constructor to initialize data members with legal initial values
void accept(): to accept n1 and n2
int getLCM(): returns the LCM of n1 and n2 using the recursive technique
void display(): to print the numbers n1, n2 and LCM
Specify the class LCM giving details of the constructor, void accept(), int getLCM() and void display(). Define a main() function to create an object and call the member functions accordingly to enable the task.
import java.util.Scanner;
class LCM{
int n1;
int n2;
int large;
int sm;
int l;
public LCM(){
n1 = 0;
n2 = 0;
large = 0;
sm = 0;
l = 0;
}
public void accept(){
Scanner in = new Scanner(System.in);
System.out.print("First number: ");
n1 = Integer.parseInt(in.nextLine());
System.out.print("Second number: ");
n2 = Integer.parseInt(in.nextLine());
if(n1 > n2){
large = n1;
sm = n2;
}
else{
large = n2;
sm = n1;
}
}
public int getLCM(){
if(large != sm){
if(large > sm)
large -= sm;
else if(large < sm)
sm -= large;
return getLCM();
}
else
return n1 * n2 / large;
}
public void display(){
System.out.println("First number: " + n1);
System.out.println("Second number: " + n2);
l = getLCM();
System.out.println("LCM: " + l);
}
public static void main(String[] args) {
LCM obj = new LCM();
obj.accept();
obj.display();
}
}