使用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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP