Find sum of even factors of a number | Formula based CPP program to find sum of all divisors of n . ; Returns sum of all factors of n . ; If n is odd , then there are no even factors . ; Traversing through all prime factors . ; While i divides n , print i and divide n ; here we remove the 2 ^ 0 that is 1. All other factors ; This condition is to handle the case when n is a prime number . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumofFactors ( int n ) { if ( n % 2 != 0 ) return 0 ; int res = 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 ; } res *= curr_sum ; } if ( n >= 2 ) res *= ( 1 + n ) ; return res ; } int main ( ) { int n = 18 ; cout << sumofFactors ( n ) ; return 0 ; }