zoukankan      html  css  js  c++  java
  • 求最大公约数的方法

    常用方法:
    辗转相除法:
    • 将两个数中较大的数放在a中,较小者放在b中,
      • 求temp=a%b
      • 判断temp是否为0
        • 为0,则b为最大公约数,
        • 不为0,b赋值给a,temp赋值给b,
        • 循环上述步骤,直到temp=0,则此时的b为最大公约数
          # Java
          public
          class maxCommonDivisor { public int max_common_divisor(int a, int b) { int anew = Math.max(a, b); int bnew = Math.min(a, b); int temp = anew % bnew; while (temp != 0) { anew = bnew; bnew = temp; temp = anew % bnew; } return bnew; } }
          # Python
          def
          max_common_divisor(a, b): # num_a为较大者,num_b为a,b的较小者 num_a = max(a, b) num_b = min(a, b) temp = num_a % num_b while temp != 0: num_a = num_b num_b = temp temp = num_a % num_b return num_b
           
    • 穷举法
      • 两种思路
        • 第一种:从a,b的较小者开始一直到1,分别被a,b除,第一个余数都为0的数则为最大公约数
           # Java
          1
          public int max_common_divisor(int a,int b){ 2 int mcd=Math.min(a,b); 3 for (int i=b;i>0;i--){ 4 if (a%i==0 && b%i==0){ 5 mcd=i; 6 break; 7 } 8 } 9 return mcd; 10 }
          # Python
          1
          def max_common_divisor(a, b): 2 result = 0 3 for i in range(min(a, b), 0, -1): 4 if a % i == 0 and b % i == 0: 5 result = i 6 break 7 return result

          # 函数调用
          res = ClassTest.max_common_divisor(20, 32)
          print(res)
        • 第二种:设置 i 从1开始到a,b的较小者,分别被a,b除,若余数均为0,则将 i 的值赋值给公约数mcd,循环结束,则mcd就是最大公约数
          # Java
          1
          public int max_common_divisor(int a,int b){ 2 int mcd=1; 3 for (int i=1;i<=Math.min(a,b);i++){ 4 if (a%i==0 && b%i==0){ 5 mcd=i; 6 } 7 } 8 return mcd; 9 }
          # Python
          def
          max_common_divisor(a, b): result = 0 for i in range(1, min(a, b) + 1): if a % i == 0 and b % i == 0: result = i return result
    • 更相减损法
  • 相关阅读:
    51nod 1134 最长递增子序列
    51nod 1135 原根
    51nod 1136 欧拉函数
    51nod 1137 矩阵乘法
    51nod 1174 区间中最大的数
    51nod 1079 中国剩余定理
    51nod 1181 质数中的质数(质数筛法)
    伪共享(False Sharing)和缓存行(Cache Line)
    mybatis 批量 操作数据
    java开发中beancopy比较
  • 原文地址:https://www.cnblogs.com/mysummary/p/12377139.html
Copyright © 2011-2022 走看看