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?

Example:

Input:  n = 12
Output: 6

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int digitSum(int n)
{
    int sum = 0;
    while (n > 0)
    {
        sum += n % 10;
        n = n / 10;
    }
    return sum;
}
int main()
{
    int n = 12;

    vector<intres;
    for (int i = 1i * i <= ni++)
    {
        if (n % i == 0)
        {
            if (n / i == i)
                res.push_back(i);
            else
            {
                res.push_back(i);
                res.push_back(n / i);
            }
        }
    }
    sort(res.begin(), res.end());
    int sum = 0ans = 0;
    for (int i = 0i < res.size(); i++)
    {
        if (digitSum(res[i]) > sum)
        {
            sum = digitSum(res[i]);
            ans = res[i];
        }
    }
    cout << ans << "\n";

    return 0;
}


No comments:

Post a Comment