Soluție HackerRank pentru Best Divisor, subdomeniul Fundamentals, în C++14. Include cerința formatată, exemple, explicația pașilor și cod sursă.
- Problemă: Best Divisor
- Domeniu: Fundamentals
- Limbaj: C++14
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
Cerință
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 ≤ 10^5
Cod sursă
#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;
}
