Extracting Prime Factors from a Non-Negative Integer

  • Share this:

Code introduction


Get all prime factors of a non-negative integer


Technology Stack : math, operator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_prime_factors(n):
    factors = []
    # 使用内置库math来获取平方根
    sqrt_n = int(n**0.5)
    for i in range(2, sqrt_n + 1):
        # 使用内置库operator来比较
        while operator.mod(n, i) == 0:
            factors.append(i)
            n = n // i
    if n > 1:
        factors.append(n)
    return factors                
              
Tags: