Finding all integers under v which are the sum of two abundant numbers

Question:

Write a function that returns a list of all the positive integers under v that can be expressed as the sum of two abundant numbers.

I’m very new to coding so it’s quite messy and I don’t even understand how half of it works. I tried multiple things, all on the premise of, I will add the 0th element with the 0th, then the 1st, then the second, until I’m adding the 0th element with the last. Then the 0th element changes to the 1st and I’m adding it to the 1st element, then the 2nd element, then the third until I’m adding the 1st element and the last.

Here is the code I’ve tried so far:

def divisors(a):
    b=[]
    for i in range(1,a):
        if a%i==0:
            b.append(i)
    if sum(b)>a:
        return True
    else:
        return False
def abundantNums(n):
    list1=[]
    for i in range(1,n):
        if divisors(i):
            list1.append(i)
            i+=1
        else:
            i+=1
    return(list1)
def AbundantSums(v):
    answers=[]
    x=0
    h=0 
    list1=[]
    for i in range(1,v):
        if divisors(i):
            list1.append(i)
            i+=1
        else:
            i+=1
    l=len(list1)
    for k in range(1,l+1):
        if list1[x]+list1[h]<=v:
            answers.append(list1[x]+list1[h])
            h+=1 
    print(answers)
Asked By: alex

||

Answers:

Here’s a sequence of functions that’ll give you what you’re after:

def divisors(a: int) -> list:
    """
    Returns a list of all the proper divisors of "a". 
    """
    b=[]
    for i in range(1,a):
    
        if a%i==0:
            b.append(i)
    return b

def is_abundant(n: int) -> bool:
    """
    Returns True if all proper divisors of "n" add up to a value greater than "n", else False.
    """
    return sum(divisors(n)) > n

def is_sum_of_two_abundant_nums(n: int) -> bool:
    """
    Returns True if "n" can be expressed as the sum of two abundant numbers, else False.
    """
    
    for i in range(1, n):
        if is_abundant(i) and is_abundant(n-i):
            return True
    return False

def AbundantSums(v: int) -> list:
    """
    Returns a list of all numbers less than "v" that can be expressed as the sum
    of two abundant numbers.
    """
    answers = []
    for i in range(1, v):
        if is_sum_of_two_abundant_nums(i):
            answers.append(i)
    return answers


# Examples of AbundantSums implemented:
    
print (AbundantSums(25))
# Result: 
#     [24]

print (AbundantSums(40))
# Result:
#     [24, 30, 32, 36, 38]

print (AbundantSums(70))
# Result:
    # [24, 30, 32, 36, 38, 40, 42, 44, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68]

Does this help?

Answered By: Vin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.