LeetCode 5178. four factor

1. Topic

To give you an array of integers nums, please return the array there are exactly four factor these integers the sum of the individual factors.

If the integer meet the meaning of the title does not exist in the array, it returns 0.

示例:
输入:nums = [21,4,7]
输出:32
解释:
214 个因数:1, 3, 7, 21
43 个因数:1, 2, 4
72 个因数:1, 7
答案仅为 21 的所有因数的和。
 
提示:
1 <= nums.length <= 10^4
1 <= nums[i] <= 10^5

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/four-divisors
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

  • Direct simulation from 2 to n / 2, when it is time consuming when a large n
class Solution {
public:
    int sumFourDivisors(vector<int>& nums) {
        int sum = 0;
        pair<bool,int> p;
        for(int i = 0; i < nums.size(); ++i)
        {
        	p = isfour(nums[i]);
            if(p.first)
                sum += p.second;
        }
        return sum;
    }

    pair<bool, int> isfour(int &n)
    {
    	if(n == 1)
    		return {false, 0};
    	int count = 2;
    	int divs = 1+n;
    	for(int i = 2; i <= n/2; ++i)
    	{
    		if(n%i == 0)
    		{
    			count++;
    			divs += i;
            }
    		if(count > 4)
    			return {false,0};
    	}
    	return {count==4,divs};
    }
};

Here Insert Picture Description

  • Since the factors in pairs, so that from 2 to traverse n \sqrt{n} To
  • Note that one pair of the case is the same factor
class Solution {
public:
    int sumFourDivisors(vector<int>& nums) {
        int sum = 0;
        pair<bool,int> p;
        for(int i = 0; i < nums.size(); ++i)
        {
        	p = isfour(nums[i]);
            if(p.first)
                sum += p.second;
        }
        return sum;
    }

    pair<bool, int> isfour(int &n)
    {
    	if(n == 1)
    		return {false, 0};
    	int count = 2;
    	int divs = 1+n;
    	for(int i = 2; i <= sqrt(n); ++i)
    	{
    		if(n%i == 0)
    		{
                if(i != n/i)
    			{
                    count += 2;
    			    divs += i+n/i;
                }
                else
                {
                    count += 1;
                    divs += i;
                }
            }
    		if(count > 4)
    			return {false,0};
    	}
    	return {count==4,divs};
    }
};

Here Insert Picture Description

Published 756 original articles · won praise 939 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105033772