This problem was posted by HackerRank
Best Divisor
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 12can 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.
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int SumDigits(int n) | |
{ | |
int sum=0; | |
while(n){ | |
sum=sum+(n%10); | |
n = n/10; | |
} | |
return sum; | |
} | |
int PrintMaxDivisor(int n) | |
{ | |
int max=0,sum=0,contender=0; | |
vector <int>v; // Vector to store half of the divisors | |
for (int i=1; i<=sqrt(n); i++){ | |
if (n%i==0){ | |
if (n/i == i){ // check if divisors are equal | |
sum = SumDigits(i); | |
if(max < sum){ | |
max = sum; | |
contender = i; | |
} | |
}else{ | |
sum = SumDigits(i); | |
if(max < sum){ | |
max = sum; | |
contender = i; | |
} | |
// push the second divisor in the vector | |
v.push_back(n/i); | |
} | |
} | |
} | |
// The vector will be printed in reverse | |
for (int i=v.size()-1; i>=0; i--){ | |
sum = SumDigits(v[i]); | |
if(max < sum){ | |
max = sum; | |
contender = v[i]; | |
} | |
} | |
return contender; | |
} | |
int main() | |
{ | |
int n; | |
cin >> n; | |
cout << PrintMaxDivisor(n); | |
return 0; | |
} |
No comments:
Post a Comment