Wednesday, January 16, 2008

HCF of a Number

Method Used :
The bigger of the two number is divided by the smaller one and remainder obtained. If the remainder is not 0 then the last divisor is divided by the remainder and another remainder is obtained . this goes on till the remainder is 0. when the remainder becomes 0,the number which is Devisor becomes HCF
Write a program To find the HCF of 2 number using above method

Evergreen Publications Model Paper unsolver Q5;

import java.io.*;
class HCF
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Enter any 2 numbers ");
int x = Integer.parseInt(br.readLine());
int y = Integer.parseInt(br.readLine());
int rem=1,re=1,h=1,s=1;
if(x>y)
{
h=x;
s=y;
}
else if(y>x)
{
h=y;
s=x;
}
do
{
rem =h%s;
if(rem>0)
{
re = s%rem;
s=rem;
rem = re;
}
else
{
System.out.println(s);
break;
}

}
while(rem>=0);

}
}

No comments: