In this article, we will learn about the solution to the problem statement given below −
Problem statement
Given a number input n, the task is to Find the sum of even factors of a number.
Here we first need to eliminate all the odd factors.
If the number input is odd it has no even factors therefor return zero directly , otherwise, we will follow the approach in the code below
Below is the implementation −
Example
import math # Returns sum of all even factors of n. def sumofFactors(n) : # If n is odd if (n % 2 != 0) : return 0 #all prime factors res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i # here we remove the 2^0 that is 1. All other factors if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # if n is prime number if (n >= 2) : res = res * (1 + n) return res # main n = 20 print(sumofFactors(n))
Output
36
All the variables are declared in the global frame as shown in the figure given below −
Conclusion
In this article, we learned about the approach to Find the sum of even factors of a number