用于查找数字偶数因子之和的 Python 程序
pythonserver side programmingprogramming更新于 2025/12/15 23:40:17
在本文中,我们将学习下面给出的问题陈述的解决方案 −
问题陈述
给定一个数字输入 n,任务是查找数字偶数因子之和。
在这里我们首先需要消除所有奇数因子。
如果输入的数字是奇数,则没有偶数因子,因此直接返回零,否则,我们将遵循以下代码中的方法
以下是实现 −
示例
import math # 返回 n 所有偶数因子之和。 def sumofFactors(n) : # 如果 n 为奇数 # If n is odd if (n % 2 != 0) : #所有素数因子 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 # 这里我们删除了 2^0,即 1。所有其他因子 if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # 如果 n 是素数 if (n >= 2) : res = res * (1 + n) return res # main n = 20 print(sumofFactors(n))
输出
36
所有变量均在全局框架中声明,如下图所示 −

结论
在本文中,我们学习了求一个数的偶数因数之和的方法
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

