Skip to content
the poor coder

Hackerrank - Best Divisor Solution

Poor Man
Published
Updated
Reading time
1 min read

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 .

Constraints

Output Format

Print an integer denoting the best divisor of .

Sample Input 0

Text
12

Sample Output 0

Text
6

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#

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())
print(bestDivisor(n))

Short version

Text
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)))))

Keep going

2020

Hackerrank - Bus Station Solution

There are groups of friends, and each group is numbered from 1 to . The th group contains people. They live near a bus stop, and only a single bus operates on this route. An empty bus arrives at the bus stop and all the…

2020

Hackerrank - K Candy Store Solution

Jim enters a candy shop which has N different types of candies, each candy is of the same price. Jim has enough money to buy K candies. In how many different ways can he purchase K candies if there are infinite candies…

2020

Hackerrank - Diwali Lights Solution

On the eve of Diwali, Hari is decorating his house with a serial light bulb set. The serial light bulb set has N bulbs placed sequentially on a string which is programmed to change patterns every second. If at least one…

ESC