Problem of The Day 14 December 2016 — Best Divisor

Ashish Patel
Codebrace
Published in
2 min readDec 14, 2016

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 13 is better than 31 and that 12 is better than 11.

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

Input Format

A single integer denoting n.

Constraints

0<n≤105

Output Format

Print an integer denoting the best divisor of n.

Sample Input 0

12

Sample Output 0

6

Explanation 0

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

Problem Link: Best Divisor

Solution will be posted tomorrow.

SOLUTION

The logic of this problem is simple.Find all the factors their sum and then sort them on the basis of the sum of digits and then print the number which has the largest sum.
So to check all the factor we go through the root of the number so our time complexity is O(sqrt(N)).
What I did is
I ran a loop from 1 to sqrt(N) and then check if the number N is divisible by it .
If it is divisible then we will get two factors let say i and N/i.
Here I use map where key is the sum and value is the factor
and then iterate through the map to find the minimum value.
See the code for more clarity and the approach.

CODE

#include<iostream>
#include<map>
using namespace std;int sumOfDigit(int n)
{
int sum=0;
while(n)
{
sum+=n%10;
n/=10;
}
return sum;
}
int main()
{
int N;
cin>>N;
int i;
map<int,int>mp;
//loop for the factors
for(i=1;i*i<=N;i++)
{
//checking if i is factor of N
if(N%i==0)
{
//we will get 2 factors here i and N/i
//mapping i and N/i

mp[sumOfDigit(i)] = i;
mp[sumOfDigit(N/i)] = N/i;
}
}
map<int,int>::iterator it;
int m=0,ans;
//iterating through map
for(it=mp.begin();it!=mp.end();++it)
{
//cout<first<<" "<second<<endl;
//checking the maximum sum
if(m < it->first)
{
ans = it->second;
m = it->first;
}
}
cout<<ans<<endl;
}

--

--

Ashish Patel
Codebrace

Big Data Engineer at Skyscanner , loves Competitive programming, Big Data.