使用 C++ 查詢數字的最小因子和。


這裡我們將瞭解如何獲取給定數字的最小因子和。假設一個數字為 12。我們可以用不同的方式對其進行分解 -

  • 12 = 12 * 1 (12 + 1 = 13)
  • 12 = 2 * 6 (2 + 6 = 8)
  • 12 = 3 * 4 (3 + 4 = 7)
  • 12 = 2 * 2 * 3 (2 + 2 + 3 = 7)

最小和為 7。我們將取一個數字,並嘗試找出最小因子和。為了獲得最小因子和,我們必須儘可能地對數字進行分解。換句話說,我們可以說,如果我們嘗試透過新增質數因子來查詢和 S,則該和將最小化。

示例

 線上演示

#include<iostream>
using namespace std;
int primeFactorSum(int n) {
   int s = 0;
   for (int i = 2; i * i <= n; i++) {
      while (n % i == 0) {
         s += i;
         n /= i;
      }
   }
   s += n;
   return s;
}
int main() {
   int n = 12;
   cout << "Minimum sum of factors: " << primeFactorSum(n);
}

輸出

Minimum sum of factors: 7

更新於: 30-Oct-2019

316 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.