DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1

Perfect Number

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.

Given an integer n, return true if n is a perfect number, otherwise return false.

Example 1:

Input: num = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.

Example 2:

Input: num = 7
Output: false

Constraints:

  • 1 <= num <= 108

SOLUTION:

class Solution:
    def getFactors(self, n, factors):
        for i in range(n - 1, 0, -1):
            if i not in factors and n % i == 0:
                factors.update({i})
                factors.update({n//i})
                self.getFactors(i, factors)

    def checkPerfectNumber(self, num: int) -> bool:
        fsum = 1
        i = 2
        while i * i <= num:
            if num % i == 0:
                fsum = fsum + i + num//i
            i += 1
        return (True if fsum == num and num!=1 else False)
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay