2010-07-05 6 views

Répondre

4

La méthode habituelle pour calculer le facteur commun le plus élevé, plus communément appelé le plus grand commun diviseur, est Euclid's algorithm.

Si vous voulez calculer la HCF de plus de deux chiffres, disent i , i , i , ..., i n, un algorithme est:

 
res = gcd(i[1], i[2]) 
for j = 3..n do 
    res = gcd(res, i[j]) 
end 
return res 
2

est ici une implémentation de Euclid's algorithm en C++:

unsigned int hcf(unsigned int a, unsigned int b) { 
    if (b == 0) { 
     return a; 
    } else { 
     return hcf(b, a % b); 
    } 
} 
1

Un code plus rapide et plus courte pour GCD

int gcd(int a, int b) { 
    while(b) b ^= a ^= b ^= a %= b; 
return a; 
} 
0

Voici le code pour calculer le HCF de deux entiers Si vous avez un problème commentaire votre requête, ne hésitez pas à demander

import java.util.*; 
class ABC{ 
     int HCF(int a,int b){ 
     int c; 
     int d; 
     c=a%b; 
     if(c==0)  
      return b; 
     else 
      return HCF(b,c); 
    } 

    public static void main(String[]args){ 
     int a,b; 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter your first number: "); 
     a= sc.nextInt(); 
     System.out.println("Enter your second number: "); 
     b=sc.nextInt(); 
     ABC obj= new ABC(); 

     if(b>a) 
      System.out.println("Wrong Input the first number must be larger than the second one"); 


     else 
      System.out.println("The H.C.F of "+a+" and "+b+" is: "+obj.HCF(a,b)); 
     }