在 C++ 程序中查找一个数的偶数因子的和?
此程序用于查找所有偶数因子并计算这些偶数因子的和然后显示为输出。
例如 −
Input : 30 Even dividers : 2+6+10+30 = 48 Output : 48
为此,我们将查找所有因子。找出其中的偶数并求和,
否则,我们将使用公式来使用素数因子求因子和,
Sum of divisors = (1 + d11 + d12 ... d1a1) *(1 + d21 + d22 ... d2a2) *...........................* (1 + dk1 + dk2 ... dkak) Here di = prime factors ; ai = power of di
我们只需要偶数因子,所以如果数字是奇数,则不存在偶数因子。因此,在这种情况下,我们将输出 0。
示例
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int n=12;
int m = n;
if (n % 2 != 0)
cout<<"The sum of all even factors of " << n <<" is "<<0;
int evfac = 1;
for (int i = 2; i <= sqrt(n); i++) {
int count = 0, curr_sum = 1, curr_term = 1;
while (n % i == 0) {
count++;
n = n / i;
if (i == 2 && count == 1)
curr_sum = 0;
curr_term *= i;
curr_sum += curr_term;
}
evfac *= curr_sum;
}
if (n >= 2)
evfac *= (1 + n);
cout <<"The sum of all even factors of " << m <>" is "<>evfac;
return 0;
}输出
The sum of all even factors of 12 is 24
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP