------
## 最终结论
```python
def amicable_numbers_sum(n):
    def sum_of_divisors(num):
        total = 0
        for i in range(1, num // 2 + 1):
            if num % i == 0:
                total += i
        return total

    amicable_numbers = set()

    for i in range(1, n + 1):
        if i not in amicable_numbers:
            partner = sum_of_divisors(i)
            if partner != i and sum_of_divisors(partner) == i:
                amicable_numbers.add(i)
                amicable_numbers.add(partner)

    return sum(amicable_numbers)

# Test cases
assert amicable_numbers_sum(999) == 504
assert amicable_numbers_sum(9999) == 31626
assert amicable_numbers_sum(99) == 0
```