Hackerrank - Best Divisor Solution
1 min read

Hackerrank - Best Divisor Solution

Hackerrank - Best Divisor Solution

Kristen loves playing with and comparing numbers. She thinks that if she takes two different positive numbers, the one whose digits sum to a larger number is better than the other. If the sum of digits is equal for both numbers, then she thinks the smaller number is better. For example, Kristen thinks that  is better than  and that  is better than .

Given an integer, , can you find the divisor of  that Kristin will consider to be the best?

Input Format

A single integer denoting .


Output Format

Print an integer denoting the best divisor of .

Sample Input 0


Sample Output 0


Explanation 0

The set of divisors of  can be expressed as . The divisor whose digits sum to the largest number is  (which, having only one digit, sums to itself). Thus, we print  as our answer.

Solution in Python

def divisors(n):
    for i in range(1,n+1):
        if not n%i:
            yield i
def bestDivisor(n):
    bestNum = 0
    bestSum = 0
    for i in divisors(n):
        s = sum(map(int,str(i)))
        if s == bestSum: 
            bestNum =  min(bestNum,i)
        elif s > bestSum:
            bestNum = i
            bestSum = s
    return bestNum

n = int(input())

Short version

n = int(input())
print(max((d for d in range(1, n+1) if n%d == 0), key=lambda x: sum(map(int, str(x)))))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.