Python 如何计算给定数的素因子指数?

Python 如何计算给定数的素因子指数?,python,prime-factoring,exponent,Python,Prime Factoring,Exponent,我刚刚完成了第三个Euler问题,它要求你找到给定数字的最大素数因子。我做了一个函数,它返回一个数的所有素数因子的列表 例如,如果输入100,它将返回[2.0,5.0] 我想尝试制作一个程序,返回一个列表,其中素数因子的出现次数与其指数相同 例如,输入100将返回[2.0,2.0,5.0,5.0](因为100是2^2*5*2) 我已经写了一个函数,如果把一个包含素数因子的列表和一个包含指数的列表放进去,这个函数可以正确地实现这一点。问题是我用来获取指数列表的函数是错误的 我写的代码对于某些数字(

我刚刚完成了第三个Euler问题,它要求你找到给定数字的最大素数因子。我做了一个函数,它返回一个数的所有素数因子的列表

例如,如果输入100,它将返回[2.0,5.0]

我想尝试制作一个程序,返回一个列表,其中素数因子的出现次数与其指数相同

例如,输入100将返回[2.0,2.0,5.0,5.0](因为100是2^2*5*2)

我已经写了一个函数,如果把一个包含素数因子的列表和一个包含指数的列表放进去,这个函数可以正确地实现这一点。问题是我用来获取指数列表的函数是错误的

我写的代码对于某些数字(18、36、50、54…)失败

我对编程相当陌生,所以如果有人能帮助我,我将非常感激

def p_fctr_exp(n):
    """Prime factorises n and gives the exponents of each factor"""
    l1 = prime_factors(n) #Initialisation of variables and lists ('prime_factors() ) is just the function I made which gives a list of the prime factors
    p = 1
    exp=[]
    result=[]
    for x in l1:    #This multiplies the prime factors together just once
        x = float(x)
        p = (p * x)
    for x in range(0,len(l1)):  
        """Loop which cycles through factors from smallest first and multiplies 
    the total by the factor until the point where one more would make it bigger
    than the target number. The number of cycles required is stored in the 
    list 'exp'""" 
        a=1
        while p<n:
            p = p*float(l1[x])
            a+=1
        if p == n:
            exp.append(a)
        elif x < len(l1)-1:
            exp.append(a-1)
    return exp
def p_fctr_exp(n):
“素数分解n并给出每个因子的指数”
l1=prime_factors(n)#变量和列表的初始化('prime_factors())就是我制作的函数,它给出了一个prime因子列表
p=1
exp=[]
结果=[]
对于l1中的x:#这只需将素因子相乘一次
x=浮动(x)
p=(p*x)
对于范围(0,len(l1))内的x:
“”“循环,循环从最小的第一个到第二个的因子
总数是按系数计算的,直到再多一个,它就会变大
所需的循环次数存储在
列出“exp”
a=1

p既然您想知道这是否是解决问题的正确方法,我建议您编写一个类似的函数来计算素数因子,只需将它们中的每一个都添加到列表中:

def prime_factors_list(n):
    result = list()
    diviser = 2

    if n <= 0:
        return [] #empty list



    if n == 1:
        return [1]

    """We increment diviser when it does not divide n anymore"""
    while n != 1:
        if n % diviser == 0: # if 'diviser' divides n
            n = n / diviser
            result.append(diviser) # diviser works, we add it to the list
        else:
            diviser += 1 #diviser does not work, we try with a bigger one

    return result
def基本因子列表(n):
结果=列表()
除数=2

如果n则应使用模运算符%。假设你有一个270号。所以,你把270除以3,直到它被“剥离”掉3,也就是说,没有3的因子了

  • 270/3=90
  • 90/3=30
  • 30/3=10
  • 10不能被3整除
270=10*33

使用素数函数:

def p_fctr_exp(n):
    primes = prime_factors(n)
    exp=[]

    for p in primes:
        e=0
            while (n%p==0):
            n=n//p       # since p still divides n,
            e+=1         # we divide n by p and increase the exponent
        exp.append(e)
    return exp
注释

  • 数论问题不要使用浮点数。首先,模运算符对它们不起作用。第二,你永远不知道什么时候你会成为精度不准确的受害者。示例:
    0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1==1.0
    计算结果为
    False。
    如果需要检查可分性,请使用%

  • 您的代码失败的原因是正确的。对于18,
    prime_因子(18)=[2,3]。
    24<18<25。您的函数报告18中2的幂为4,这是错误的


  • 这将完成工作

    cpu的内存使用可能存在这种折衷。在这里,我试图保持素数列表小,如果它足以进行因式分解

    import math
    
    class PrimeList():
        init_primes = [2,3,5,7,11,13,15,17,19,23]
        def __init__(self, n):
            self.primes = PrimeList.init_primes
            self.extend(n)
    
        def extend(self,n):
            n = int(n)
            nextnum = self.primes[-1]
            while(self.primes[-1]<n):
                nextnum += 2
                if self.check(nextnum):
                    self.primes.append(nextnum)
    
        def check(self,n):
            n = int(n)
            limit = int(math.sqrt(n))
            return all((n%p for p in self.primes if p<=limit))
    
        def is_prime(self, n):
            n = int(n)
            self.extend(int(math.sqrt(n)))
            return self.check(n)
    
        def factors(self, n):
            n = int(n)
            x = n
            fact = dict()
            for p in self.primes:
                if p>x:
                    break
                while x%p==0:
                    x = x/p
                    fact[p]=fact.get(p,0)+1
            if x>1:
                e = x if x!=n else int(math.sqrt(n))
                self.extend(e)
                return self.factors(n)
            return sorted(fact.items())
    
    
    
    myprimes = PrimeList(25)
    print "cached primes:"+str(myprimes.primes)
    print "100 == "+str(myprimes.factors(100))
    print "32768 == "+str(myprimes.factors(32768))
    print "23! == "+str(myprimes.factors(math.factorial(23)))
    print "cached primes: "+str(myprimes.primes)
    print "10001 == "+str(myprimes.factors(10001))
    print "cached primes:"+str(myprimes.primes)
    

    好奇的是:素数总是整数,那你为什么要返回浮点数呢?请修正你的缩进。我认为它返回浮点数是因为我的函数找到素数因子的方式(可能是不必要的卷积),它进行除法以查看答案是否为整数,但如果我没有使用浮点除法,则答案始终为整数。不过,这似乎没什么区别,所以我就把它忘了。我认为缩进现在应该解决同样的问题:非常感谢!这比我试图做的更有意义,我已经使用了这段代码,现在它工作得非常完美。了解浮动也非常有用,这解释了为什么我在尝试时不断出错!谢谢,这个链接真的很有用,我也一直在努力学习如何在我的课程中使用NumPy,所以很高兴看到它是如何实现的。
    cached primes:[2, 3, 5, 7, 11, 13, 15, 17, 19, 23, 29]
    100 == [(2, 2), (5, 2)]
    32768 == [(2, 15)]
    23! == [(2, 19), (3, 9), (5, 4), (7, 3), (11, 2), (13, 1), (17, 1), (19, 1), (23, 1)]
    cached primes: [2, 3, 5, 7, 11, 13, 15, 17, 19, 23, 29]
    10001 == [(73, 1), (137, 1)]
    cached primes:[2, 3, 5, 7, 11, 13, 15, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137]