[leetcode] prime factorization

topic

Participating in the weekly competition for the first time, I encountered prime factorization...
Topic: https://leetcode.cn/problems/split-the-array-to-make-coprime-products/description/

solution

First, traverse the array and decompose the prime factor of each number. The hash table map records the subscript of the first occurrence of the prime factor, and the array right records the rightmost subscript with the same prime factor as right[i]. After the traversal is completed, the right array will be very useful, because the right array records the non-coprime numbers farthest from right[i],

class Solution {
    
    
public:
    int findValidSplit(vector<int>& nums) {
    
    
        int len = nums.size();
        unordered_map<int, int> map;
        vector<int> right(len, 0);
        for (int i = 0; i < len; i++) {
    
    
            right[i] = i;
        }
        for (int i = 0; i < len; i++) {
    
    
            int x = nums[i];
            for (int d = 2; d*d <= x; d++) {
    
    
                if (x%d == 0) {
    
    
                    //TODO: update right
                    if (map.find(d) != map.end()) {
    
    
                        right[map[d]] = i;
                    } else {
    
    
                        map[d] = i;
                    }
                    for (x /= d; x % d == 0; x /= d);
                }
            }
            if (x > 1) {
    
    
                //TODO: update right
                if (map.find(x) != map.end()) {
    
    
                    right[map[x]] = i;
                } else {
    
    
                    map[x] = i;
                }
            }
        }
        int right_end = 0;
        for (int i = 0; i < len-1; i++) {
    
    
            right_end = max(right_end, right[i]);
            if (i == right_end) {
    
    
                return i;
            }
        }
        return -1;
    }
};

The template for prime factorization is as follows. This may seem inconvenient, but it's fast :

// check x
vector<int> ans;
for (int d = 2; d*d <= x; d++) {
    
    
    if (x%d == 0) {
    
    
        ans.push_back(d);
        for (x /= d; x % d == 0; x /= d);
    }
}
if (x > 1) {
    
    
	ans.push_back(x);
}

The following method is also prime factorization, it seems very convenient but the speed is very slow, it will time out, don't use it!

// check x
vector<int> ans;
for (int d = 2; x > 1; d++) {
    
    
    if (x%d == 0) {
    
    
        ans.push_back(d);
        for (x /= d; x % d == 0; x /= d);
    }
}

Guess you like

Origin blog.csdn.net/weixin_43742643/article/details/129358567
Recommended