Greatest Common Divisor from a set of more than 2 integers

后端 未结 13 1030
遇见更好的自我
遇见更好的自我 2020-12-09 04:25

There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function

13条回答
  •  爱一瞬间的悲伤
    2020-12-09 05:24

    Here's the C# version.

      public static int Gcd(int[] x) {
          if (x.length < 2) {
              throw new ArgumentException("Do not use this method if there are less than two numbers.");
          }
          int tmp = Gcd(x[x.length - 1], x[x.length - 2]);
          for (int i = x.length - 3; i >= 0; i--) {
              if (x[i] < 0) {
                  throw new ArgumentException("Cannot compute the least common multiple of several numbers where one, at least, is negative.");
              }
              tmp = Gcd(tmp, x[i]);
          }
          return tmp;
      }
    
      public static int Gcd(int x1, int x2) {
          if (x1 < 0 || x2 < 0) {
              throw new ArgumentException("Cannot compute the GCD if one integer is negative.");
          }
          int a, b, g, z;
    
          if (x1 > x2) {
              a = x1;
              b = x2;
          } else {
              a = x2;
              b = x1;
          }
    
          if (b == 0) return 0;
    
          g = b;
          while (g != 0) {
              z= a % g;
              a = g;
              g = z;
          }
          return a;
      }
    
    }
    

    Source http://www.java2s.com/Tutorial/Java/0120__Development/GreatestCommonDivisorGCDofpositiveintegernumbers.htm

提交回复
热议问题