Finding HCF and LCM of Two Numbers In Java


Write a program to LCM and HCF of two integers.

 

import java.io.*;

class HCM

{

int a,b,num,hcd,hcm;

void lcm()

{

a=Integer.parseInt(System.console().readLine(“enter the first no.=”));

b=Integer.parseInt(System.console().readLine(“enter the 2nd   no.=”));

int m=a*b;

if(a>b)

{

num=a;

}

else

{

num=b;

}

for (int i = 1; i <= num; i++)

{

if ((a%i==0) && (b%i==0))

{

hcd=i;

}

}

System.out.println(“HCF=”+hcd);

hcm=m/hcd;

System.out.println(“LCM=”+hcm);

}

public static void main(String[] args)

{

HCM ab = new HCM();

ab.lcm();

}

}

Finding HCF and LCM of Two Numbers In Java

This java program accepts two  from the user and prints their HCF and LCM

import java.util.*;
class hcfandlcm
{
public static void main(String Args[])
{
System.out.println(“Enter 2 numbers”);
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();

int h=1;
int p=m*n;
for(int i=2;i<p;i++)
{
if((m%i==0)&&(n%i==0))
{
h=i;
}
}
int l=p/h;
System.out.println(“HCF=”+h+” and LCM=”+l);
}

}

 

 

 

Related Posts

Comments are closed.