C++ 中的四因子


假設我們有一個整數陣列 nums,我們需要找到該陣列中恰好有四個因子的整數的因子之和。如果陣列中沒有這樣的整數,則返回 0。例如,如果輸入為 [21, 4, 7],則輸出將為 32,因為 21 有四個因子 1、3、7、21,4 有三個因子 1、2、4,7 有兩個因子 1 和 7。答案僅為 21 的因子之和。

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個名為 ok() 的方法,它將以 x 作為輸入

  • ret := 1 + x, cnt := 2

  • for i := 2, i^2 <= x, i 增加 1

    • 如果 x 可以被 i 整除

      • ret 增加 i,cnt 增加 1

      • 如果 i 不等於 x/i,則 cnt 增加 1,ret := ret + (x/i)

  • 如果 cnt 為 4,則返回 ret,否則返回 0

  • 從主方法

  • ret := 0, n := nums 的大小

  • for i in range 0 to n – 1

    • ret := ret + ok(nums[i])

  • 返回 ret

示例(C++)

讓我們看看以下實現以更好地理解:

 即時演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int ok(int x){
      int ret = 1 + x;;
      int cnt = 2;
      for(int i = 2; i * i <= x; i++){
         if(x % i == 0){
            ret += (i);
            cnt++;
            if(i != x / i){
               cnt++;
               ret += (x / i);
            }
         }
      }
      return cnt == 4 ? ret : 0;
   }
   int sumFourDivisors(vector<int>& nums) {
      int ret = 0;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         ret += ok(nums[i]);
      }
      return ret;
   }
};
main(){
   vector<int> v = {21,4,7};
   Solution ob;
   cout << (ob.sumFourDivisors(v));
}

輸入

[21,4,7]

輸出

32

更新於: 2020年4月29日

455 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.