Q:

Java - Greatest Common Factor or Euclidean Algorithm Program or Highest Common Factor

belongs to collection: Java Basic Programs

0

Java - Greatest Common Factor or Euclidean Algorithm Program or Highest Common Factor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Greatest Common Factor / Euclidean Algorithm Program / Highest Common Factor

import java.util.Scanner;
 
public class HCF {
  
    //  greatest common factor
    public static int hcf(int First_number, int Second_number) {
         int hcf=0;
         int min = Math.min(First_number,Second_number);
           
         for(int i=min; i >= 1; i--)
         {
             if(First_number%i == 0 && Second_number%i == 0)
             {
                 hcf = i;
                 break;
             }
         }  
         return hcf;
    }
  
    public static void main(String[] args) {
      
        Scanner sc=new Scanner(System.in);
 
        System.out.print("First Number  :");
        int num1=sc.nextInt();
        System.out.print("Second Number :");
        int num2=sc.nextInt();
 
        System.out.println("Highest Common Factor: " + hcf(num1,num2));
       
    }
}

Output

    First Number  :24
    Second Number :16
    Highest Common Factor: 8

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java - Calculate LCM (Least Common Multiple) using... >>
<< Java - Greatest Common Divisor or Euclidean Algori...