Problem: Deficient Number

*Difficulty: Easy

iven a number x, your task is to find if this number is Deficient number or not. A number x is said to be Deficient Number if sum of all the divisors of the number denoted by divisorsSum(x) is less than twice the value of the number x. And the difference between these two values is called the deficiency.

Mathematically, if below condition holds the number is said to be Deficient:
divisorsSum(x) < 2*x
deficiency = (2*x) – divisorsSum(x)
Examples:

Input: 21
Output: YES
Divisors are 1, 3, 7 and 21. Sum of divisors is 32.
This sum is less than 2*21 or 42.

Input: 12
Output: NO

Input: 17
Output: YES

 

Input:
The first line of input contains an integer T denoting the no of test cases.
Then T test cases follow. Each line contains an integer x.

Output:
For each test case in a new line print 1 if the no is a Deficient number else print 0.

Constraints:
1<=T<=10000
1<=x<=10000
Example:
Input:

3
21
12
17
Output:
1
0
1

 

How to solve:
Using prime factorization 

Implementation: Python 2.7

def get_primes():
    """
        an efficient way to calculate prime numbers
    """
    yield 2
    yield 3
    i = 5
    while True:
        yield i
        if i%6 == 1:
            i += 2
        i += 2

def get_prime_factors(n):
    """
        get prime factors of a number
    """
    d = {}
    primes = get_primes()
    for p in primes:
        while n % p == 0:
            n /= p
            d[p] = d.setdefault(p, 0) + 1
        if n == 1:
            return d 

def sum_of_divisors(d, n):
    if len(d) == 1: #n is a prime number
        return n+1
    s = 1
    for factor in d.keys():
        s *= ((1-pow(factor, d[factor]+1))/(1-factor))
    return s

if __name__ == '__main__':
    t = input()
    for _ in range(t):
        n = input()
        prime_factors = get_prime_factors(n)
        if sum_of_divisors(prime_factors, n) < n*2:
            print 1
        else:
            print 0

Advertisements