简体   繁体   English

如何查找每次迭代中获得的最大值以将其追加到列表中

[英]how to find maximum of values obtained in each iteration to append it to a list

Given a number n , write a program to find the sum of the largest prime factors of each of nine consecutive numbers starting from n . 给定数字n ,编写一个程序以查找从n开始的九个连续数字中每个数字的最大素数和。

I am able to get the factors but for each value if there are multiple factors which are prime I want only the maximum values among the those prime factors which I can't get. 我能够得到这些因子,但是对于每个值,如果有多个质数因子,我只想要那些我无法获得的质数因子中的最大值。

def find_g(num):
    factor=[]
    list1=[]
    list2=[]
    for i in range(0,num-1):
        factor.append(num+i)
    print(factor)
    for f in factor:
        for i in range(2,f+1):
            if(f%i==0 and i%2!=0):
                list1.append(i)
                print(list1)
                list2.append(max(list1))
        list1=[]

    print(list2)

print(find_g(10))

Input: 10 输入10
Desired Output: [5, 11, 3, 13, 7, 5, 17, 9] 所需的输出: [5, 11, 3, 13, 7, 5, 17, 9] 5、11、3、13、7、5、17、9 [5, 11, 3, 13, 7, 5, 17, 9]
Actual Output: [5, 11, 3, 13, 7, 3, 5, 15, 17, 3, 9] 实际输出: [5, 11, 3, 13, 7, 3, 5, 15, 17, 3, 9]

You can break this down into two parts: (A) find the largest prime factor for any given number n , and (B) sum the largest prime factors of each of nine consecutive numbers starting from n . 您可以将其分解为两部分:(A)找到任意给定数字n的最大素数,(B)从n开始对九个连续数字中的每一个的最大素数求和。 I'll describe code for each, and then combine them. 我将描述每种代码,然后将它们组合。

(A) We can find the largest prime factor for a number n , lpf(n) , with the below code: (A)我们可以使用以下代码找到数字n的最大素数: lpf(n)

def lpf(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
    return n

(B) Then, we can run this code for each number from n to n+9 by mapping the lpf function across range(n, n+9) and summing the result: (B)然后,我们可以通过跨range(n, n+9)映射lpf函数并对结果求和来为从nn+9的每个数字运行此代码。

def find_g(n):
    return sum(map(lpf, range(n, n+9)))

For your case of n=10 , we get 对于n=10 ,我们得到

find_g(10) = 66

This is correct because the largest prime factors for [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] are, respectively, [5, 11, 3, 13, 7, 5, 2, 17, 3]. 这是正确的,因为[10、11、12、13、14、15、16、17、18、19]的最大素数分别为[5、11、3、13、7、5、2、17 ,3]。

(Note that your expected answer is incorrect, can you figure out why?) (请注意,您的预期答案不正确,您能找出原因吗?)

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

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