zoukankan      html  css  js  c++  java
  • common divisors两个数字的所有共同除数

    思路:就是把gcd拆一下,因为如果GCD可以,这些数就也可以
    3,6

    gcd = n = 3

    1/3 没了,0 += 2

    GCD辗转相除法:b一开始是除数,后来是余数。余数为0就行了

    16 4

    4,4

    4,0

    所以返回a = 4

    https://www.geeksforgeeks.org/common-divisors-of-two-numbers/

    // Java implementation of program 
    
    class Test { 
        // method to calculate gcd of two numbers 
        static int gcd(int a, int b) 
        { 
            if (a == 0) 
                return b; 
    
            return gcd(b % a, a); 
        } 
        // method to calculate all common divisors 
        // of two given numbers 
        // a, b --> input integer numbers 
        static int commDiv(int a, int b) 
        { 
            // find gcd of a, b 
            int n = gcd(a, b); 
    
            // Count divisors of n. 
            int result = 0; 
            for (int i = 1; i <= Math.sqrt(n); i++) { 
                // if 'i' is factor of n 
                if (n % i == 0) { 
                    // check if divisors are equal 
                    if (n / i == i) 
                        result += 1; 
                    else
                        result += 2; 
                } 
            } 
            return result; 
        } 
    
        // Driver method 
        public static void main(String args[]) 
        { 
            int a = 12, b = 24; 
            System.out.println(commDiv(a, b)); 
        } 
    } 
    View Code
  • 相关阅读:
    阅读笔记十四
    惨淡的蓝桥杯国赛经历
    阅读笔记十三
    阅读笔记十二
    阅读笔记十一
    阅读笔记十
    阅读笔记九
    阅读笔记八
    阅读笔记七
    阅读笔记六
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13877105.html
Copyright © 2011-2022 走看看