Monday, July 26, 2010

To find the greatest common factor?

How do you write a program in Java to find the greatest common factor?

import java.util.Scanner;

public class Gcd
{

public static void main(String args[])
{
int temp=0,i;

Scanner s=new Scanner(System.in);

System.out.println("enter 2 numbers");

int a=s.nextInt();

int b=s.nextInt();

for(i=2;i<=a;i++)
{
if(a%i==0)
{
if(b%i==0)

temp=i;

}//end of if

}//end of for

System.out.println("Gcd is:");

System.out.println(temp);

}//end of main

}//end of class

No comments: