2010-07-05 38 views

回答

4

計算最高公因數的常用方法,通常稱爲最大公約數,爲Euclid's algorithm

如果要計算超過兩個號碼的HCF,說 ,...,ñ,一個算法是:

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

這裏是Euclid's algorithm在C++中實現:

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

的GCD

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

這裏更快和更短的代碼是計算兩個整數的HCF代碼 如果您有任何問題發表評論您的查詢,隨便問

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)); 
     }