簡體   English   中英

從數組中查找互質元素的高效快捷方式

[英]Efficient and faster way to find coprimes elements from an array

我正在做一個小項目。 我的任務是在數組中查找與所有其他值互質的元素。 我想出了一個使用雙 for 循環的方法。 但是,我相信時間復雜度不會很好,尤其是在元素數組很大的情況下。

這些是我所擁有的:

ArrayList<Integer> getAllCoPrimes(int[] inputs) {
    ArrayList<Integer> coprimes = new ArrayList<>();
    int[] elementsCount = new int[inputs.length];
    for (int i = 0; i < inputs.length; i++) {
        int x = inputs[i];
        for (int j = 0; j < inputs.length; j++) {
            int y = inputs[j];
            if (i != j) {
                if (gcd(x, y) == 1) {
                    elementsCount[i]++;
                    if (elementsCount[i] == inputs.length) //x is a coprime with all the elements in the array
                        coprimes.add(x);
                }
            }
        }
    }
    return coprimes;
}

static int gcd(int a, int b) {
  // Everything divides 0
  if (a == 0 || b == 0)
    return 0;

  // base case
  if (a == b)
    return a;

  // a is greater
  if (a > b)
    return gcd(a - b, b);

  return gcd(a, b - a);
}

我想問一下有什么方法可以改進我的方法以更有效地運行嗎? 先感謝您 :)

您的算法目前是 O(n^2*log(S))。 n = 項目數,S = 數字的大小

我相信它可以在 O(n*n) 中實現(這不一定是很大的收益)。

  • 為此,您首先要計算數組中每個元素的素因數(可以在 O(log(S))中實現,其中 S 是數字的大小。
  • 將結果存儲在每個數字的列表中(因此您將擁有 N 個列表)。 這些列表的平均長度將是這里給出的質因子的平均數量: https : //en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93Kac_theorem# :~: text= The% 20Erd%C5%91s%E2%80%93Kac%20theorem%20means,需要%20on%20average%20three%20素數
  • 創建一個反向映射,為每個質因子提供具有該質因子的數字的索引
  • 然后再次循環遍歷所有數字,並為每個數字循環遍歷它們的質因數(這或多或少是基於數字大小的常數)並減去共享公共質因數的數字。 然后,您將看到互質數列表。 對於每個數字,這一步是 O(n)。

注意:您可能對原始代碼沒問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM