Challenge: Best Divisor

Subdomeniu: Fundamentals (fundamentals)

Scor cont: 20.0 / 20

Submission status: Accepted

Submission score: 1.0

Submission ID: 464720195

Limbaj: cpp14

Link challenge: https://www.hackerrank.com/challenges/best-divisor/problem

Cerinta

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$.

Output Format

Print an integer denoting the best divisor of $n$.

Constraints

* $0 \lt n \le 10^5$

Cod sursa

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int solve(int n)
{
    int sum=0;
    while(n>=1)
    {
        sum=sum+n%10;
        n=n/10;
    }
    return sum;
}   

int main() {
    
    int n;cin>>n;
    int sum,ans,maxi=0;
    for(int i=1;i<=n;++i)
    {
        if(n%i==0)
        {
            sum=solve(i);
            if(maxi<sum)
            {
                maxi=sum;ans=i;
            }
            if(maxi==sum)
            { ans=min(i,ans);}
        }
    }
    cout<<ans<<endl;
}
HackerRank Fundamentals – Best Divisor