求一個數的偶數因子的和的 C++ 程式?
在本節中,我們將瞭解如何高效地獲得一個數的所有偶數質因子的和。有一個數,比如 n = 480,我們要取得它的所有因子。480 的質因子是 2、2、2、2、2、3、5。所有偶數因子的和為 2+2+2+2+2 = 10。要解決這個問題,我們必須遵循以下規則:-
當該數被 2 整除時,將其新增到和中,並重復將該數除以 2。
現在這個數一定是個奇數。因此,我們找不到任何偶數因子。然後直接忽略這些因子。
讓我們看看該演算法以獲得更好的想法。
演算法
printPrimeFactors(n)
begin sum := 0 while n is divisible by 2, do sum := sum + 2 n := n / 2 done end
示例
#include<iostream> using namespace std; int sumEvenFactors(int n){ int i, sum = 0; while(n % 2 == 0){ sum += 2; n = n/2; //reduce n by dividing this by 2 } return sum; } main() { int n; cout << "Enter a number: "; cin >> n; cout << "Sum of all even prime factors: "<< sumEvenFactors(n); }
輸出
Enter a number: 480 Sum of all even prime factors: 10
廣告