Find sum of even factors of a number using C++.


In this section, we will see how we can get the sum of all even prime factors of a number in an efficient way. There is a number say n = 480, we have to get all factors of this. The prime factors of 480 are 2, 2, 2, 2, 2, 3, 5. The sum of all even factors is 2+2+2+2+2 = 10. To solve this problem, we have to follow this rule −

  • When the number is divisible by 2, add them into the sum, and divide the number by 2 repeatedly.
  • Now the number must be odd. So we will not find any factors which are even. Then simply ignore those factors.

Let us see the algorithm to get a better idea.

Algorithm

printPrimeFactors(n):
begin
   sum := 0
   while n is divisible by 2, do
   sum := sum + 2
   n := n / 2
   done
end

Example

 Live Demo

#include<iostream>
using namespace std;
int sumEvenFactors(int n){
   int i, sum = 0;
   while(n % 2 == 0){
      sum += 2;
      n = n/2; //reduce n by dividing this by 2
   }
   return sum;
}
main() {
   int n;
   cout << "Enter a number: ";
   cin >> n;
   cout << "Sum of all even prime factors: "<< sumEvenFactors(n);
}

Output

Enter a number: 480
Sum of all even prime factors: 10

Updated on: 30-Oct-2019

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements