To find sum of even factors of a number in C++ Program?


This program is used to find all the even factors and calculate the sum of these even factors and display it as output.

Example −

Input : 30
Even dividers : 2+6+10+30 = 48
Output : 48

For this, we will find all the factors. Find the even of them and find the sum,

Else, we will use the formula to find the sum of factors using the prime factors,

Sum of divisors = (1 + d11 + d12 ... d1a1) *(1 + d21 + d22 ... d2a2) *...........................* (1 + dk1 + dk2 ... dkak)
Here di = prime factors ; ai = power of di

We need only even factors so, if the number is odd then no even factor exists. So, we will output 0 in that case.

Example

#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;
}

Output

The sum of all even factors of 12 is 24

Updated on: 30-Oct-2019

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements