如何用最简单的python方法求一个数的因子

2024-05-12 11:41:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找到一个数的所有因子,并在列表中列出因子。在

输入:

   >>>factors(72)

输出:

^{pr2}$

我已经取下了一些代码,因为这有很多视图,这是一个硬件问题,所以我不想它被复制。在


Tags: 代码视图列表硬件因子factorspr2
3条回答
def factors(n):
a = []
x = 2
while x * x <= n :
    if n % x == 0:          
        a.append(x)
        n /= x
    else: x += 1
if n > 1: a.append(n)
return a

所有人都尽快投了否决票。在

这是一个使用素数分解的解决方案。它要快得多。在

import bisect
import math
import pathlib


primes = []
last_prime = None


def _get_primes():
    """
    Load all the primes in global primes. Set global last_prime to last prime
    read.
    """

    global primes
    global last_prime
    path_to_primes = pathlib.Path(__file__).parent \
            .joinpath('../resources/primes.txt')
    with path_to_primes.open() as file:
        for line in file:
            for n in line.split():
                n = n.strip()
                if n:
                    n = int(n)
                    primes.append(n)
    last_prime = primes[-1]


def gen_primes_before(n):
    """
    Generates all the primes before n in reverse order.
    """

    assert n <= last_prime, "Maximum value for n is {}".format(last_prime)
    pos = bisect.bisect_left(primes, n)
    if pos:
        yield from primes[:pos]


def gen_factors(n):
    """
    Generates all the factors of a number. May return some values multiple
    times. Values returned are not ordered.
    """
    type_n = type(n)
    assert type_n is int or (type_n is float and n.is_integer()), "Wrong type"
    n = int(n)
    r = int(math.sqrt(n)) + 1
    assert r <= last_prime, "n is over limit"
    yield 1
    yield n
    for prime in gen_primes_before(r):
        partner = n/prime
        if partner.is_integer():
            yield from gen_factors(prime)
            yield from gen_factors(partner)


def get_factors(n):
    """
    Get all the factors of n as a sorted list.
    """
    return sorted(set(gen_factors(n)))


_get_primes()
if __name__ == '__main__':
    l = (1e9,)
    for n in l:
        print("The factors of {} are {}".format(n, get_factors(n)))

我做了一个仓库:https://github.com/Pierre-Thibault/Factor

关于你的问题1:factoring is hard。这就是为什么它是许多密码算法的核心——我们目前还不知道一种快速将一个非常大的数字因子化的方法。在

对于小数字,你的算法就可以了。对于稍微大一点的数字,我已经得到了same question-显然Pollard的Rho是一个很好的算法。对于大量的人,我们不知道。在

现在回答你的问题2:

首先,在您的prime(n)函数中,您不需要一直检查if n%i==0,直到n。您只需要检查到sqrt(n),因为如果有任何一对整数(a,b),这样a * b = n,那么这些整数中的一个必然小于或等于sqrt(n)。所以你只需要检查sqrt(n)。这样可以节省大量计算。在

这是您的factors函数:

from math import ceil

def factors(n):
        factors = []
        while n > 1:
                for i in range(2,int((ceil(n/2.0))+1)):
                        if n%i==0:
                                factors.append(i)
                                n = n/i
                                continue
                factors.append(n)
                break
        return factors

相关问题 更多 >