4

配列 a に n 個の整数が格納されています。たとえば、a[0]、a[1]、.....、a[n-1] で、それぞれa[i] <= 10^12n <100. ここで、これらの n 個の整数の最小公倍数 ({a[0],a[1],.....,a[n-1]} の最小公倍数) のすべての素因数を見つける必要があります。

方法はありますが、より効率的な方法が必要です。

私の方法:

 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 が提案したように、私のコードには、ふるいの高速化やマイナーな変更などの最適化が必要でした。これらすべての変更を行った後、問題を解決できました。これは、1.05 秒かかった SPOJ で受け入れられたコードです。

#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

FWIWは、すべての素数を100万まで取得するためのより高速な方法を求める当初の要求に応えて、これを行うためのはるかに高速な方法を示します。

これは、ウィンドウサイズのエラトステネスのホイールベースのふるいを使用します。ホイールサイズは30で、ウィンドウサイズは検索の上限の平方根に設定されています(最大1,000,000の検索の場合は1000)。

私はC++に習熟していないため、C ++に簡単に変換できることを前提として、C#でコーディングしました。ただし、C#でも、約10ミリ秒で1,000,000までのすべての素数を列挙できます。10億までのすべての素数を生成するのにかかる時間はわずか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 に答える
2

これらの制約により、大きすぎない数がいくつかあるため、それらの最小公倍数の素因数分解を見つける最良の方法は、実際には各数値の因数分解です。10 6未満の素数は 78498 個しかないため、試行分割は十分に高速であり (パフォーマンスの最後の低下がどうしても必要でない限り)、素数を 10 6にふるい分けるのも数ミリ秒です。

速度が最も重要である場合は、試行分割と、ポラードのロー アルゴリズムまたは楕円曲線因数分解法のような因数分解法を使用した決定論的 Miller-Rabin 型プライム テストを組み合わせたアプローチが、おそらくもう少し高速です (ただし、数値は非常に小さいです)。その差は大きくなく、素数テストと因数分解を高速に行うには、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]]複数回設定しないでください。s がかなり高速であってもstd::map、1 回だけ設定するよりも遅くなります。

于 2012-03-17T19:16:43.837 に答える
1

http://en.wikipedia.org/wiki/Least_common_multipleにはいくつかの有用なアルゴリズムがあるようです

特にhttp://en.wikipedia.org/wiki/Least_common_multiple#A_method_using_a_table
が適切なようです。

ネストされたループを「裏返し」にして、一度に素数を 1 つずつ、すべての数値を同時に処理します。

一度に 1 つの素数を使用するため、必要に応じて次の素数を見つけることができ、開始前に 10^6 の素数を生成することを回避できます。各数値が素因数によって減数されると、数値をテストするために必要な最大素数が減る可能性があるため、必要な作業はさらに少なくなります。

編集:また、すべての要因が見つかったときに数が1つに減るため、終了が明確になり、確認が容易になります。実際、コードでそのプロパティを使用していませんが、すべての数値が 1 になると終了する可能性があります。

編集: 問題を読みました。 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) 最悪の場合、78,498 個の素数をテストする必要がある 100 個の数値、= 7,849,800 の「mod」操作があります。

log2(10^12) = 43 個の剰余と 43 個の剰余を超える素数 (1 個の剰余と 1 個の除算) で因数分解できる数はありません。簡単にするために、8,000,000 の整数除算と mod と呼びましょう。素数を生成する必要がありますが、Daniel Fischer が既に述べたように、それは迅速です。あとは簿記です。

したがって、最新のプロセッサでは、約 1,000,000,000 分割または 1 秒あたりの mod を WAG するので、実行時間は約 10ms 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

の 100 の999962000357L, // ((long)999979L)*((long)999983L)

gcc --version i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. ビルド 5666) (ドット 3) Copyright (C) 2007 Free Software Foundation, Inc. これはフリー ソフトウェアです。条件のコピーについてはソースを参照してください。保証はありません。商品性や特定の目的への適合性のためでさえありません。

モデル名: MacBook Pro プロセッサ名: Intel Core 2 Duo プロセッサ速度: 2.16 GHz

概要: これは明らかに機能し、実行時間は、Daniel Fischer の実装に匹敵する比較的古いプロセッサで、許容最大値の約 20% です。

質問: 私はここに寄稿したばかりなので、次
の場合に私の回答に -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 に答える