使用 C++ 查詢某個數字的“奇數”因數和。
在本節中,我們將瞭解如何高效獲得一個數字的所有奇數質因數之和。有一個數字為 n = 1092,我們必須獲取此數字的所有因數。1092 的質因數為 2、2、3、7、13。所有奇數因數之和為 3+7+13 = 23。要解決這個問題,我們必須遵循以下規則 −
- 當該數字可以被 2 整除時,忽略該因數,並重復將該數字除以 2。
- 現在這個數字一定是奇數。現在從 3 開始到該數字的平方根,如果該數字可以被當前值整除,則將該因數新增到和中,並將該數字除以當前數字得到的新數字,然後繼續。
- 最後,如果剩餘數字是奇數,則也會將該剩餘數字加到和中
讓我們看看這個演算法,以便更好地理解。
演算法
printPrimeFactors(n): begin sum := 0 while n is divisible by 2, do n := n / 2 done for i := 3 to , increase i by 2, do while n is divisible by i, do sum := sum + i n := n / i done done if n > 2, then if n is odd, then sum := sum + n end if end if end
示例
#include<iostream>
#include<cmath>
using namespace std;
int sumOddFactors(int n){
int i, sum = 0;
while(n % 2 == 0){
n = n/2; //reduce n by dividing this by 2
}
//as the number is not divisible by 2 anymore, all factors are odd
for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers
while(n % i == 0){
sum += i;
n = n/i;
}
}
if(n > 2){
if(n%2 == 1)
sum += n;
}
return sum;
}
main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout <<"Sum of all odd prime factors: "<< sumOddFactors(n);
}輸出
Enter a number: 1092 Sum of all odd prime factors: 23
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP