给定数字的HCF

时间:2010-07-05 10:40:42

标签: algorithm

计算给定数字的HCF的逻辑是什么?

6 个答案:

答案 0 :(得分:4)

计算最高公因数(通常称为最大公约数)的常用方法是Euclid's algorithm

如果您想计算两个以上数字的HCF,请说 i 1 i 2 i 3 ,..., i n ,一种算法是:

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

答案 1 :(得分:2)

以下是C ++中Euclid's algorithm的实现:

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

答案 2 :(得分:1)

更快更短的GCD代码

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

答案 3 :(得分:0)

这是计算两个整数的H.C.F的代码 如果您对查询有任何问题,请随时提出

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

答案 4 :(得分:0)

通过这种方式,无论输入顺序如何,它都将起作用:

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();
    System.out.println("The H.C.F of " + a + " and " + b + " is: " + HCF(a,b));
}

private static int HCF(int a, int b) {

    int c;
    if (a > b) {
        c = a % b;
        if (c == 0)
            return b;
        else
            return HCF(b, c);
    } else {
        c = b % a;
        if (c == 0)
            return a;
        else
            return HCF(a, c);
    }
}

答案 5 :(得分:0)

LoadLibrary

这会给出答案。