python-3.x - 如何高效地找到适当因子的多重性?

标签 python-3.x algorithm numbers number-theory

我正在尝试编写代码来找出给定数字是否是 n 的适当因子,同时我还试图找出给定数字的重数。

这是我的代码:

def f(n, d):
    '''
    >>> f(2, 1)
    1 is not a proper factor of 2.
    >>> f(2, 2)
    2 is not a proper factor of 2.
    >>> f(16, 2)
    2 is a proper factor of 16 of mutiplicity 4.
    >>> f(100, 20)
    20 is a proper factor of 100 of mutiplicity 1.
    >>> f(8 ** 7 * 3 ** 5 * 11 ** 2, 8)
    8 is a proper factor of 61662560256 of mutiplicity 7.
    >>> f(3 ** 3 * 11 * 13 ** 2 * 40 ** 6, 8)
    8 is a proper factor of 205590528000000 of mutiplicity 6.
    '''
    multiplicity = 0
    # Insert your code here
    if d == 1:
        print(f'{d} is not a proper factor of {n}.')
    if d == n:
        print(f'{d} is not a proper factor of {n}.')
    if n % d == 0:
        copy = n
        while(copy != 1):
            copy = copy // d
            multiplicity += 1
    if not multiplicity:
        print(f'{d} is not a proper factor of {n}.')
    else:
        print(f'{d} is a proper factor of {n} of mutiplicity {multiplicity}.')


if __name__ == '__main__':
    import doctest
    doctest.testmod()

任何建议都会有很大帮助。

最佳答案

如果我没有正确理解你想做什么,我相信这个循环有错误的条件

while(copy != 1):
    copy = copy // d
    multiplicity += 1

只要副本是 d 的倍数,你想要的是将副本除以 d,即

while(copy % d == 0):
    copy = copy / d
    multiplicity += 1

关于python-3.x - 如何高效地找到适当因子的多重性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581533/

相关文章:

python - 将 pandas 中的数字格式化为以千或百万为单位的货币

python-3.x - 将文档添加到 gensim 模型

python gnupg 如何对文件进行 pgp 加密,而无需指定 homedir,或将 key 存储在目录中

python - 使用简单的 PyQT UI 选择目录路径粉碎

c++ - 对于受 CPU 限制的应用程序,您会推荐哪种语言/平台?

algorithm - 在基于DCEL/半边的图中动态添加边?

php - 用随机字符替换字符串中的每个数字

php - 四舍五入到小数点后第二位

python - 如何在 KivyMD 中选择目录和文件

algorithm - 在不损失精度的情况下有效地逼近第 n 项