在 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