使用 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