Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2521. Distinct Prime Factors of Product of Array

Rain Hu

2521. Distinct Prime Factors of Product of Array


一、題目

Given an array of positive integers nums, return the number of distinct prime factors in the product of the elements of nums.
Note that:

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Sieve of Eratosthenes

vector<int> table;      // 在全域建一個 pre-built table
int distinctPrimeFactors(vector<int>& nums) {
    int upbound = *max_element(nums.begin(), nums.end());   // 求整個數列的最大值
    table.assign(upbound+1, 0);                             // table 只需求到最大值即可
    iota(table.begin(), table.end(), 0);                // 依序將 table[i] = i 填入 table

    for (int i = 2; i <= upbound; i++) {
        if (!table[i]) continue;                        // 當該數為合數時,跳過
        for (int j = 2*i; j <= upbound; j += i) {
            table[j] = i;                               // 將所有質數的倍數記錄下他
        }
    }
    
    unordered_set<int> set;                             
    for (const auto& num : nums) {
        find(num, set);                                 // 質因數分解
    }
    return set.size();                                  // 求質因數的個數
}
void find(int num, unordered_set<int>& set) {
    if (table[num] == num) {
        set.insert(num);                                // 當是質數就用 set 記錄下來
    } else {
        find(num/table[num], set);                      // 不是質數就繼續分解
        find(table[num], set);
    }
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 520. Detect Capital
Next
[LeetCode] 2520. Count the Digits That Divide a Number