要在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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语