简体   繁体   English

查找多个质因数 Python

[英]Find multiple prime factors Python

I have to write code that finds prime factors.我必须编写代码来查找主要因素。 Also, I have to keep in mind the factors that appear multiple times.另外,我必须记住多次出现的因素。 For 12, I know how to write the code that returns 3 and 2.对于 12,我知道如何编写返回 3 和 2 的代码。

def prime_factors(n):
for possible_prime in range(2,int(math.sqrt(n)+1)):
    redundant=n%possible_prime
    if redundant==0:
        for last_check in range(2,int(math.sqrt(possible_prime)+1)):
            redundant2=possible_prime%last_check
            if redundant2!=0:
                print(possible_prime)

But what I need to get is 2, 2, 3. Can anyone help?但我需要得到的是 2, 2, 3。有人可以帮忙吗? I am supposed to use loops and lists.我应该使用循环和列表。

Thanks in advance.提前致谢。

Shai沙伊

It is often better to keep things simple and stupid (KISS principle).保持简单和愚蠢通常更好(KISS 原则)。 Although there are more efficient algorithms to do prime factorization, this one is straight forward:虽然有更有效的算法来进行质因数分解,但这个算法很简单:

import math

def prime_factors(n):
    res = []
    # handle factors 2 first
    while n%2 == 0: 
        res.append(2)
        n = n//2
    fac = 3
    # handle all odd factors until limit reached
    while fac < int(math.sqrt(n))+1:
        while n%fac == 0:
            res.append(fac)
            n = n//fac
        fac += 2
    # append remaining prime factor
    if n > 2:
        res.append(n)
    return res

print (prime_factors(2222222222))

Note use of // for integer division in Python 3.注意在 Python 3 中使用//进行整数除法。

First of all you should remove all even numbers from the range() to optimize the loop, I would also suggest adding one to the integer form of the sqrt to keep types consistent.首先,您应该从range()删除所有偶数以优化循环,我还建议在 sqrt 的整数形式中添加一个以保持类型一致。 The second loop is not optimized either, as every time the first loop results in a redundant == 0 the possible prime is either prime or a combination of already found primer factors, thus reducing the amount of numbers you need to check against第二个循环也没有优化,因为每次第一个循环导致redundant == 0 ,可能的素数要么是素数,要么是已经找到的引物因子的组合,从而减少了您需要检查的数字数量

def prime_factors(n):
    factors = []
    for possible_prime in [2] + range(3, int(math.sqrt(n))+1, 2):
        if not (n % possible_prime):
            limit = int(math.sqrt(possible_prime)
            is_prime = True
            for factor in factors:
                if factor > limit:
                    break
                if not (possible_prime % factor):
                    is_prime = False
                    break
            if is_prime:
                factors.append(possible_prime)
    return factors

As you said, this gives you all prime factors, now we just want to duplicate (or further) if apropiate:正如您所说,这为您提供了所有主要因素,现在我们只想复制(或进一步)如果 apropiate:

def prime_factors(n):
    factors = []
    for possible_prime in [2] + range(3, int(math.sqrt(n))+1, 2):
        if not (n % possible_prime):
            limit = int(math.sqrt(possible_prime)
            is_prime = True
            for factor in factors:
                if factor > limit:
                    break
                if not (possible_prime % factor):
                    is_prime = False
                    break
            if is_prime:
                factors.append(possible_prime)
    factors_copy = factors[:]
    for factor in factors_copy:
        i = 0
        j = n
        while not(j % factor):
            i += 1
            j /= factor
        for k in range(i-1):
            factors.append(factor)
    return sorted(factors)

I am new to Python but will give it a try (please correct me if the synthax is not perfect)我是 Python 新手,但会尝试一下(如果 synthax 不完美,请纠正我)

def prime_factors(n):
    prime_list = []
    job_done = False
    first_prime = 2
    while not job_done:
        for possible_prime in range(first_prime,n+1):
            if n%possible_prime == 0:
                prime_list.append(possible_prime)
                first_prime = possible_prime
                n = int(n/possible_prime)
                if n == 1:
                    job_done = True
                break
    return prime_list

Here is an example of how to find prime factors using recursion and walrus operator这是一个如何使用递归和海象算子找到素因数的例子

def prime_factors(n):
    for i in range(2, int(n ** 0.5) + 1):
        if (q_r := divmod(n, i))[1] == 0:
            return [i] + factor_list(q_r[0])
    return [n]
>>> prime_factors(12)
[2, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM