4

我有 n 个整数存储在数组 a 中,比如 a[0],a[1],.....,a[n-1] 其中每个a[i] <= 10^12n <100. 现在,我需要找到这 n 个整数的 LCM 的所有质因数,即 {a[0],a[1],.....,a[n-1]} 的 LCM

我有一种方法,但我需要一种更有效的方法。

我的方法:

 First calculate all the prime numbers up to 10^6 using sieve of Eratosthenes.

 For each a[i]
      bool check_if_prime=1;
      For all prime <= sqrt(a[i])
             if a[i] % prime[i] == 0 {
                store prime[i]
                check_if_prime=0
             }
      if check_if_prime
             store a[i]     // a[i] is prime since it has no prime factor <= sqrt(n) 
  Print all the stored prime[i]'s

有没有更好的方法来解决这个问题?

我正在发布问题的链接:

http://www.spoj.pl/problems/MAIN12B/

链接到我的代码: http: //pastebin.com/R8TMYxNz

解决方案:

正如 Daniel Fischer 所建议的,我的代码需要一些优化,比如更快的筛子和一些小的修改。完成所有这些修改后,我能够解决问题。这是我在 SPOJ 上接受的代码,耗时 1.05 秒:

#include<iostream>
#include<cstdio>
#include<map>
#include<bitset>

using namespace std;

#define max 1000000

bitset <max+1> p;
int size;
int prime[79000];

void sieve(){
    size=0;
    long long i,j;
    p.set(0,1);
    p.set(1,1);
    prime[size++]=2;
    for(i=3;i<max+1;i=i+2){
        if(!p.test(i)){
            prime[size++]=i;
            for(j=i;j*i<max+1;j++){
                p.set(j*i,1);
            }
        }
    }
}

int main()
{
    sieve();

    int t;
    scanf("%d", &t);

    for (int w = 0; w < t; w++){
        int n;
        scanf("%d", &n);
        long long a[n];

        for (int i = 0; i < n; i++)
            scanf("%lld", &a[i]);

        map < long long, int > m;
        map < long long, int > ::iterator it;
        for (int i = 0; i < n; i++){
            long long num = a[i];
            long long pp;
            for (int j = 0; (j < size) && ((pp = prime[j]) * pp <= num); j++){
                int c = 0;
                for ( ; !(num % pp); num /= pp)
                    c = 1;
                if (c)
                    m[pp] = 1;
            }

            if ((num > 0) && (num != 1)){
                m[num] = 1;
            }
        }
        printf("Case #%d: %d\n", w + 1, m.size());
        for (it = m.begin(); it != m.end(); it++){
            printf("%lld\n", (*it).first);
        }
    }

    return 0;
}

如果有人能够以更好的方式或更快的方法做到这一点,请告诉我。

4

4 回答 4

2

有了这些限制,一些不太大的数字,找到它们的最小公倍数的素因数分解的最佳方法确实是每个数字的因式分解。由于低于 10 6的素数只有 78498个,因此试除法将足够快(除非您真的非常渴望性能的最后下降),并且将素数筛选为 10 6也只需几毫秒。

如果速度是最重要的,那么试验除法和确定性 Miller-Rabin 类型素数测试的组合方法以及像 Pollard 的 rho 算法或椭圆曲线因式分解方法这样的因式分解方法可能会快一点(但数字是如此之小差异不会很大,并且您需要一个超过 64 位的数字类型才能快速进行素性测试和分解)。

在分解中,您当然应该删除发现的主要因素

if (a[i] % prime[k] == 0) {
    int exponent = 0;
    do {
        a[i] /= prime[k];
        ++exponent;
    }while(a[i] % prime[k] == 0);
    // store prime[k] and exponent
    // recalculate bound for factorisation
}

以减少您需要检查素数的限制。

据我所知,您的主要问题是您的筛子太慢并且占用了太多空间(这部分是其缓慢的原因)。使用一点筛子来获得更好的缓存局部性,从筛子中删除偶数并停止检查是否在max. 而且您为主要数组分配了太多空间。

for(int j=0;(prime[j]*prime[j] <= num) && (j<size);j++){

您必须j < size在访问前检查prime[j]

    while(num%prime[j]==0){
        c=1;
        num /= prime[j];
        m[prime[j]]=1;
    }

不要设置m[prime[j]]多次。即使std::maps 非常快,也比只设置一次要慢。

于 2012-03-17T19:16:43.837 回答
2

FWIW,为了响应最初要求以更快的方式使所有素数达到一百万的请求,这里有一种更快的方法来做到这一点。

这使用基于窗口轮的 Eratosthenes 筛,轮子大小为 30,窗口大小设置为搜索上限的平方根(1000 表示搜索高达 1,000,000)。

由于我不精通 C++,因此我用 C# 对其进行了编码,假设这应该可以轻松转换为 C++。然而,即使在 C# 中,它也可以在大约 10 毫秒内枚举所有素数,最多可达 1,000,000。即使生成所有高达十亿的素数也只需要 5.3 秒,我想这在 C++ 中会更快。

public class EnumeratePrimes
{
    /// <summary>
    /// Determines all of the Primes less than or equal to MaxPrime and
    /// returns then, in order, in a 32bit integer array.
    /// </summary>
    /// <param name="MaxPrime">The hishest prime value allowed in the list</param>
    /// <returns>An array of 32bit integer primes, from least(2) to greatest.</returns>
    public static int[] Array32(int MaxPrime)
    {
        /*  First, check for minimal/degenerate cases  */
        if (MaxPrime <= 30) return LT30_32_(MaxPrime);

        //Make a copy of MaxPrime as a double, for convenience
        double dMax = (double)MaxPrime;

        /*  Get the first number not less than SQRT(MaxPrime)  */
        int root = (int)Math.Sqrt(dMax);
        //Make sure that its really not less than the Square Root
        if ((root * root) < MaxPrime)  root++;

        /*  Get all of the primes <= SQRT(MaxPrime) */
        int[] rootPrimes = Array32(root);
        int rootPrimeCount = rootPrimes.Length;
        int[] primesNext = new int[rootPrimeCount];

        /*  Make our working list of primes, pre-allocated with more than enough space  */
        List<int> primes = new List<int>((int)Primes.MaxCount(MaxPrime));
        //use our root primes as our starting list
        primes.AddRange(rootPrimes);

        /*  Get the wheel  */
        int[] wheel = Wheel30_Spokes32();

        /*  Setup our Window frames, starting at root+1 */
        bool[] IsComposite; // = new bool[root];
        int frameBase = root + 1;
        int frameMax = frameBase + root; 
        //Pre-set the next value for all root primes
        for (int i = WheelPrimesCount; i < rootPrimeCount; i++)
        {
            int p = rootPrimes[i];
            int q = frameBase / p;
            if ((p * q) == frameBase) { primesNext[i] = frameBase; }
            else { primesNext[i] = (p * (q + 1)); }
        }

        /*  sieve each window-frame up to MaxPrime */
        while (frameBase < MaxPrime)
        {
            //Reset the Composite marks for this frame
            IsComposite = new bool[root];

            /*  Sieve each non-wheel prime against it  */
            for (int i = WheelPrimesCount; i < rootPrimeCount; i++)
            {
                // get the next root-prime
                int p = rootPrimes[i];
                int k = primesNext[i] - frameBase;
                // step through all of its multiples in the current window
                while (k < root) // was (k < frameBase) ?? //
                {
                    IsComposite[k] = true;  // mark its multiple as composite
                    k += p;                 // step to the next multiple
                }
                // save its next multiple for the next window
                primesNext[i] = k + frameBase;
            }

            /*  Now roll the wheel across this window checking the spokes for primality */
            int wheelBase = (int)(frameBase / 30) * 30;
            while (wheelBase < frameMax)
            {
                // for each spoke in the wheel
                for (int i = 0; i < wheel.Length; i++)
                {
                    if (((wheelBase + wheel[i] - frameBase) >= 0)
                        && (wheelBase + wheel[i] < frameMax))
                    {
                        // if its not composite
                        if (!IsComposite[wheelBase + wheel[i] - frameBase])
                        {
                            // then its a prime, so add it to the list
                            primes.Add(wheelBase + wheel[i]);
                        }
                        // // either way, clear the flag
                        // IsComposite[wheelBase + wheel[i] - frameBase] = false;
                    }
                }
                // roll the wheel forward
                wheelBase += 30;
            }

            // set the next frame
            frameBase = frameMax;
            frameMax += root;
        }

        /*  truncate and return the primes list as an array  */
        primes.TrimExcess();
        return primes.ToArray();
    }

    // return list of primes <= 30
    internal static int[] LT30_32_(int MaxPrime)
    {
        // As it happens, for Wheel-30, the non-Wheel primes are also
        //the spoke indexes, except for "1":
        const int maxCount = 10;
        int[] primes = new int[maxCount] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };

        // figure out how long the actual array must be
        int count = 0;
        while ((count <= maxCount) && (primes[count] < MaxPrime)) { count++; }

        // truncte the array down to that size
        primes = (new List<int>(primes)).GetRange(0, count).ToArray();
        return primes;
    }
    //(IE: primes < 30, excluding {2,3,5}.)

    /// <summary>
    /// Builds and returns an array of the spokes(indexes) of our "Wheel".
    /// </summary>
    /// <remarks>
    /// A Wheel is a concept/structure to make prime sieving faster.  A Wheel
    /// is sized as some multiple of the first three primes (2*3*5=30), and
    /// then exploits the fact that any subsequent primes MOD the wheel size
    /// must always fall on the "Spokes", the modulo remainders that are not
    /// divisible by 2, 3 or 5.  As there are only 8 spokes in a Wheel-30, this
    /// reduces the candidate numbers to check to 8/30 (4/15) or ~27%.
    /// </remarks>
    internal static int[] Wheel30_Spokes32() {return new int[8] {1,7,11,13,17,19,23,29}; }
    // Return the primes used to build a Wheel-30
    internal static int[] Wheel30_Primes32() { return new int[3] { 2, 3, 5 }; }
    // the number of primes already incorporated into the wheel
    internal const int WheelPrimesCount = 3;
}

/// <summary>
/// provides useful methods and values for working with primes and factoring
/// </summary>
public class Primes
{
    /// <summary>
    /// Estimates PI(X), the number of primes less than or equal to X,
    /// in a way that is never less than the actual number (P. Dusart, 1999)
    /// </summary>
    /// <param name="X">the upper limit of primes to count in the estimate</param>
    /// <returns>an estimate of the number of primes between 1  and X.</returns>
    public static long MaxCount(long X)
    {
        double xd = (double)X;
        return (long)((xd / Math.Log(xd)) * (1.0 + (1.2762 / Math.Log(xd))));
    }
}
于 2012-03-19T18:12:25.953 回答
1

http://en.wikipedia.org/wiki/Least_common_multiple似乎有几种有用的算法

特别是http://en.wikipedia.org/wiki/Least_common_multiple#A_method_using_a_table
似乎是合适的。

它将嵌套循环“从里到外”翻转并同时处理所有数字,一次一个素数。

因为它一次使用一个素数,您可以根据需要找到下一个素数,避免在开始之前生成 10^6 个素数。由于每个数字都减少了其素数,因此测试这些数字所需的最大素数可能会减少,因此它需要的工作更少。

编辑:它还使终止明确且易于检查,因为在找到所有因素后,该数字会减少到一。事实上,当所有数字都减少到一个时,它可以终止,尽管我没有在我的代码中使用该属性。

编辑:我读了这个问题,http ://en.wikipedia.org/wiki/Least_common_multiple#A_method_using_a_table 的算法直接解决了它。

SWAG:10^6 以下有 78,498 个素数 (http://primes.utm.edu/howmany.shtml#table) 所以最坏的情况下,有 100 个数字需要针对 78,498 个素数进行测试,= 7,849,800 'mod' 操作

没有一个数可以通过质数(一个模和一个除法)成功分解超过 log2(10^12) = 43 个模和除法,因此 4,300 个除法和 4,300 个模数,因此由质数测试主导。为了简单起见,我们称之为 8,000,000 整数除法和模数。它需要生成素数,但正如 Daniel Fischer 已经说过的那样,这很快。剩下的就是记账了。

所以,在现代处理器上,我会 WAG 大约 1,000,000,000 个除法或 mods/秒,所以运行时间大约为 10 毫秒 x 2?

编辑:我在http://en.wikipedia.org/wiki/Least_common_multiple#A_method_using_a_table使用了算法

没有聪明,就像那里解释的那样。

我严重超出了我的估计,大约 10 倍,但仍然只有最大允许运行时间的 20%。

性能(通过一些打印来确认结果)

real 0m0.074s
user 0m0.062s
sys  0m0.004s

100 个号码:

999979, 999983, 999979, 999983, 999979, 999983, 999979, 999983, 999979, 999983,

10 次,以确保必须测试几乎所有素数,因为这似乎是主要的计算。

并且打印量相同,但值几乎为 10^12

real 0m0.207s
user 0m0.196s
sys  0m0.005s

对于 100999962000357L, // ((long)999979L)*((long)999983L)

gcc --version i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3) 版权所有 (C) 2007 Free Software Foundation, Inc. 这是免费软件;查看复制条件的来源。没有保修;甚至不考虑适销性或特定用途的适用性。

型号名称:MacBook Pro 处理器名称:Intel Core 2 Duo 处理器速度:2.16 GHz

总结:在相对较旧的处理器上,它显然可以工作,并且运行时间约为允许最大值的 20%,这与 Daniel Fischer 的实现相当。

问题:我是这里的新贡献者,所以在以下情况下 -2 我的答案似乎有点苛刻
:它似乎准确、完整并满足所有标准,并且
b. 我写了代码,测试了它,并提供了结果
我做错了什么?我如何获得反馈以便改进?

于 2012-03-17T18:34:44.220 回答
0
result := []

for f in <primes >= 2>:
   if (any a[i] % f == 0):
      result = f:result
   for i in [0..n-1]:
      while (a[i] % f == 0):
         a[i] /= f
   if (all a[i] == 1):
      break

注意:这只给出了 LCM 的主要因素列表,而不是 LCM 的实际值(即不计算指数),我相信这是所有需要的问题。

于 2012-03-18T00:09:00.057 回答