Project Euler Problem #23

#Python program to find the sum of non abundant numbers with test cases
import unittest

def sum_divisor(num):
    if num<0:
        num*=-1
    divisors_sum = 1
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            divisors_sum += i
            if i != num // i:
                divisors_sum += num // i
    if divisors_sum>num:
        return True
    else:
        return False


def abundant_num(num):
    list=[]
    for i in range(2,num):
        if sum_divisor(i):
            list.append(i)
    return list

def sum_abundant_num(num):
    abundant_num_list=abundant_num(num)
    abundant_sums=set()
    for i in range(0,len(abundant_num_list)):
        for j in range(i,len(abundant_num_list)):
            abundant_sum = abundant_num_list[i]+abundant_num_list[j]
            if abundant_sum < 28124:
                abundant_sums.add(abundant_sum)
            else:
                break
    return abundant_sums

def sum_non_abundant(num):
    sum_abundant = sum_abundant_num(num)
    non_abundant=0
    for i in range(1,num):
        if i not in sum_abundant:
            non_abundant+=i
    return non_abundant

print(sum_non_abundant(28124))


class test_cases(unittest.TestCase):
    def test_sum_divisor(self):
        self.assertEqual(sum_divisor(-10),False)
        self.assertEqual(sum_divisor(25),False)
        self.assertEqual(sum_divisor(30),True)

    def test_abundant_num(self):
        self.assertEqual(abundant_num(30),[12,18,20,24])
        self.assertEqual(abundant_num(60),[12,18,20,24,30,36,40,42,48,54,56])
        self.assertEqual(abundant_num(70),[12,18,20,24,30,36,40,42,48,54,56,60,66])

    def test_sum_abundant_num(self):
        self.assertEqual(sum_abundant_num(-55),set())
        self.assertEqual(sum_abundant_num(30),{24, 30, 32, 36, 38, 42, 40, 44, 48})
        self.assertEqual(sum_abundant_num(24),{24, 30, 32, 36, 38, 40})

    def test_sum_non_abundant(self):
        self.assertEqual(sum_non_abundant(24),276)
        self.assertEqual(sum_non_abundant(0),0)
        self.assertEqual(sum_non_abundant(-50),0)


if __name__ == "__main__":
    unittest.main()
0
Subscribe to my newsletter

Read articles from Varjinth subramaniyan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Varjinth subramaniyan
Varjinth subramaniyan