简体   繁体   中英

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 .

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
Desired Output: [5, 11, 3, 13, 7, 5, 17, 9]
Actual Output: [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 . 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:

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:

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

For your case of n=10 , we get

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].

(Note that your expected answer is incorrect, can you figure out why?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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