
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of Even Factors of a Number in 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 factor 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 factor which are even. Then simply ignore those factors.
Let us see the algorithm to get better idea.
Algorithm
printPrimeFactors(n)
begin sum := 0 while n is divisible by 2, do sum := sum + 2 n := n / 2 done end
Example
#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
Advertisements