快速找到两组数字中的普通素数除数

时间:2015-12-13 13:37:50

标签: c++ math optimization primes

我一直试图解决这个问题:https://codility.com/programmers/task/common_prime_divisors/

我在返回正确的答案方面有所帮助,但对于较大的数字而言它非常慢,我想看看是否有人更好地采取更快的做法或解释我可以优化它的方法。

bool IsPrime(int number)
{
    for (int i = 2; i < number; i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }

    return true;    
}

bool GetPrimeFactors(int valueA, int valueB)
{
    if(valueA < 0 || valueB < 0)
        return false;

    int max = sqrt(std::max(valueA, valueB)) + 1;//sqrt(std::max(valueA, valueB));
    std::vector<int> factors;
    bool oneSuccess = false;
    for(int i = 2; i <= max; i++)
    {
        bool remainderA = valueA % i == 0;
        bool remainderB = valueB % i == 0;
        if(remainderA != remainderB)
            return false;
        if(IsPrime(i))
        {
            //bool remainderA = valueA % i == 0;
           // bool remainderB = valueB % i == 0;

            if(remainderA != remainderB )
            {
                return false;
            }
            else if(!oneSuccess && remainderA && remainderB)
            {
                oneSuccess = true;
            }
        }
    }

    return true;
}

int solution(vector<int> &A, vector<int> &B) {
    int count = 0;
    for(size_t i = 0; i < A.size(); i++)
    {
        int valA = A[i];
        int valB = B[i];

        if(GetPrimeFactors(valA, valB))
            ++count;
    }

    return count;
}

6 个答案:

答案 0 :(得分:8)

您实际上不必找到数字的素因子来决定它们是否具有相同的素因子。

这是我考虑过的一般算法,用于检查ab是否具有相同的素因子。这比素数分解ab快得多。

  1. 如果a == b,答案为true
  2. 如果a == 1 || b == 1,答案为false
  3. 使用Euclid's Algorithm查找2个数字的GCD。如果是GCD == 1,则答案为false
  4. 请注意,GCD需要包含两个数字的所有素因子才能使答案成立,因此请检查newa = a/GCDnewb = b/GCD是否可以减少为1重复将Euclid(newa, GCD)Euclid(newb, GCD)分开,直到newanewb达到1成功,或Euclid(newa, GCD)Euclid(newb, GCD)返回1这是一个失败。
  5. Let's see how this works for a = 75, b = 15:
    
    1) GCD = Euclid(75, 15) = 15
    2) newa = 75/15 = 5, newb = 15/15 = 1, done with newb
    3) newa = 5/Euclid(15, 5) = 5/5 = 1 success!
    
    How about a = 6, b = 4:
    
    1) GCD = Euclid(6, 4) = 2
    2) newa = 6/2 = 3, newb = 4/2 = 2
    3) Euclid(2, newa) = Euclid(2, 3) = 1 fail!
    
    How about a = 2, b = 16:
    
    1) GCD = Euclid(2, 16) = 2
    2) newa = 2/2 = 1 (that's good), newb = 16/2 = 8
    3) newb = 8/Euclid(2, 8) = 8/2 = 4
    4) newb = 8/Euclid(2, 4) = 2
    5) newb = 2/Euclid(2, 2) = 1 success!
    

答案 1 :(得分:2)

一个(非常简单)优化(更新):

bool IsPrime(int number)
{
    if (number % 2 == 0) 
    {
        return (number == 2);
    }
    int limit = sqrt(number);
    for (int i = 3; i <= limit; i += 2)
    {
        if (number % i == 0)
        {
            return false;
        }
    }
    return true;    
}

答案 2 :(得分:0)

找到了很好且非常详细的解释here

假设两个数字NM,并用质数分解,然后将NM的GCD表示为P1 * P2 * P3 * P4 * ... Px(每个这些是gcd(N,M)的主要除数。然后,将N / gcd(N,M)M / gcd(N,M)分别用其主要除数表示为N1 * N2 * N3 * ... NyM1 * M2 * M3 * ... Mz;那么NM可以表示如下。

N = (P1 * P2 * P3 ... Px) * N1 * N2 * N3 * ... Ny
M = (P1 * P2 * P3 ... Px) * M1 * M2 * M3 * ... Mz

由于(P1 * P2 * P3 ... Px)gcd(N,M),因此NM(P1, P2, P3, ... Px)共有的任何主除数总是至少出现一次。

换句话说,如果在N/ gcd(N,M)中找不到'(N1, N2, N3 ... Ny)'(P1, P2, P3, ...Px)的任何主要除数,则它不是M的主要除数。因此,可以说NM的素数除数的集合并不完全相同。

类似地,如果在M / gcd(A,B)中找不到'(M1, M2, L3 ... Ly)'(P1, P2. P3, ... Px)的任何主要除数,则它不是N的主要除数,可以是说NM的素数集并不完全相同。

因此问题只是检查N1-NyM1-Mz中是否没有出现在P1-Px中。

现在让我们考虑一下。让X = N / gcd(N,M)并考虑gcd(gcd(N, M), X)

现在,将如下。

gcd(N,M): P1 * P2 * P3 ... Px
X       : N1 * N2 * N3 ... Ny

如果gcd(N,M) % X == 0,则X的所有主要除数都包含在gcd(N,M)中。

如果不是,则我们计算gcd(gcd(N,M), X)。如果这两个值的gcd仅为1,则表示N1-Ny中没有P1-Px出现;这意味着值N具有一个与M不共享的质数。

如果gcd大于1,则我们计算X / gcd(gcd(N,M), X),并在下一轮更新X。这意味着我们取出了构成X的{​​{1}}的一些主要除数,并将其用于下一轮

如果此时gcd(gcd(N,M), X),则表示gcd(N, M) % X == 0的所有主要除数都包含在X中。如果没有,我们将再次执行上述操作。

答案 3 :(得分:0)

上述@vacawama解决方案的python实现。

def gcd_division(a, b):
    if not a%b:
        return b
    return gcd_division(b, a%b)

def prime_reduce(n, gcd):
    na = n // gcd
    ngcd = gcd_division(na, gcd)
    if na == 1:
        return True # success base case
    elif ngcd == 1:
        return False
    return prime_reduce(na, ngcd)

def solution(A, B):
    Z = len(A)
    result = 0
    for i in range(0, Z):
        a, b = A[i], B[i]
        if a == b:
            result += 1
        else:
            gcd = gcd_division(a, b)
            result += (prime_reduce(a, gcd) and prime_reduce(b, gcd))
    return result

我用以下测试用例来运行它。

if __name__ == '__main__':
    test_cases = (
        (1, ([15, 10, 9], [75, 30, 5]) ),
        (2, ([7, 17, 5, 3], [7, 11, 5, 2]) ),
        (2, ([3, 9, 20, 11], [9, 81, 5, 13]) ),
    )
    for expected, args in test_cases:
        got = solution(*args)
        print('result', expected, got)
        assert(expected == got)

其100%https://app.codility.com/demo/results/training7KRXR3-FE5/

答案 4 :(得分:0)

基于vacawama的答案的Java实现:

  class Solution {
    public int solution(int[] A, int[] B) {
        int count = 0;
        for(int i = 0; i < A.length; i++){
            if(A[i] == B[i]) count++;
            else if(A[i] == 1 || B[i] == 1) continue;
            else{
                int GCD = gcd(A[i], B[i]);
                
                if(GCD == 1) continue;
                
                int newA = A[i]/GCD;
                int newB = B[i]/GCD;
                
                if(checkDiv(newA, GCD) && checkDiv(newB, GCD)) count++;
            } 
        }
        
        return count;
    }
    
    public boolean checkDiv(int num, int gcd){
        
        if(num == 1) return true;
        else if(gcd == 1) return false;
        
        else {
            gcd = gcd(gcd, num);
            num = num/gcd;
        
            return checkDiv(num, gcd);
        }
    }
    public int gcd(int a, int b){
        if(b == 0) return a;
        else return gcd(b, a % b);
    }
}

答案 5 :(得分:0)

使用@vacawama 回答的Javascript 解决方案。 100% 的可塑性


function solution(A, B) {

    function getGcd(a,b, res = 1) {
        if (a === b) return res * a;
        if (a % 2 === 0 && b % 2 === 0) return getGcd(a/2, b/2, 2 * res);
        if (a % 2 === 0) return getGcd(a/2, b, res);
        if (b % 2 === 0) return getGcd(a, b/2, res);
        if (a > b) return getGcd(a-b, b, res);
        else return getGcd(a, b-a, res);
    }

    const hasCommonPrimeDivisors = (a, b) => {
        if (a === b) return true;
        if (a === 1 || b === 1) return false;
        let gcd = getGcd(a, b);
        if (gcd === 1) return false;
        while (a !== 1 || b !== 1) {
            let newGcd;
            if (a !== 1) {
                newGcd = getGcd(a, gcd);
                if (newGcd === 1) {
                    return false;
                }
                a = a / newGcd;
            }

            if (b !== 1) {
                newGcd = getGcd(b, gcd);
                if (newGcd === 1) {
                    return false;
                }
                b = b/newGcd;
            }
        }
        return true;
    }

    let count = 0
    A.forEach((a, index) => {
        const b = B[index];
        if (hasCommonPrimeDivisors(a, b)) {
            count++;
        }
    })
    return count;
}
相关问题