Perfect Number Checker

Check if a number is perfect, deficient, or abundant. Find proper divisors and divisor sums.

Find Perfect Numbers

Known Perfect Numbers

Часто задаваемые вопросы

Реализация кода

def get_proper_divisors(n: int) -> list[int]:
    """Get all proper divisors of n (excluding n itself)."""
    if n <= 1:
        return []
    divisors = [1]
    i = 2
    while i * i <= n:
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n // i)
        i += 1
    return sorted(divisors)

def check_perfect(n: int) -> dict:
    """Check if n is perfect, deficient, or abundant."""
    if n <= 0:
        return {"error": "Must be positive"}

    divisors = get_proper_divisors(n)
    divisor_sum = sum(divisors)

    if divisor_sum == n:
        classification = "perfect"
    elif divisor_sum < n:
        classification = "deficient"
    else:
        classification = "abundant"

    return {
        "number": n,
        "divisors": divisors,
        "divisor_sum": divisor_sum,
        "is_perfect": divisor_sum == n,
        "classification": classification,
        "difference": n - divisor_sum
    }

# Known perfect numbers
perfect_numbers = [6, 28, 496, 8128, 33550336]
for p in perfect_numbers:
    r = check_perfect(p)
    print(f"{p}: {r['classification']} (divisors sum = {r['divisor_sum']})")
    print(f"  Divisors: {r['divisors']}")

# Find abundant numbers up to 100
print("\nAbundant numbers up to 100:")
abundant = [n for n in range(2, 101) if check_perfect(n)["classification"] == "abundant"]
print(abundant)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.