Find largest sum of digits in all divisors of n in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer n. Our task is to find the largest sum of digits in all divisors of n. 

Problem  Description: Here, we will find the divisor of the number n whose sum of digits in largest.

Let’s take an example to understand the problem, 

Input: 18

Output: 9

Explanation: 

All divisors of 18 are 1, 2, 3, 6, 9, 18.

The maximum digits sum is 9.

Solution Approach

Find all divisors of the number N. And then find the sum of digits of each divisors and then return the value with the largest sum.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int calcDigitSum(int n) {
   
   int sum = 0;
   while (n != 0) {
      sum = sum + n % 10;
      n = n/10;
   }
   return sum;
}

int largestDigitSumdivisior(int n) {
   
   int maxSum = 0;
   for (int i = 1; i <= n; i++)
      if (n % i == 0)
      maxSum = max(maxSum, calcDigitSum(i));

   return maxSum;
}

int main() {
   
   int n = 45;
   cout<<"The divisor with largest sum of digits is "<<largestDigitSumdivisior(n)<<endl;
   return 0;
}

Output

The divisor with largest sum of digits is 9

The solution can be made more effective using modifying the method to find the divisor and making it more effective.

In this problem, we will iterate till sqrt(n) and find all divisors and other divisors are calculated using n/div. This reduces the time complexity to find divisors to sqrt(n). 

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int calcDigitSum(int n) {
   
   int sum = 0;
   while (n != 0) {
      sum = sum + n % 10;
      n = n / 10;
   }
   return sum;
}

int largestDigitSumdivisior(int n) {
   
   int maxSum = 0;
   for (int i = 1; i*i <= n; i++) {

      if (n % i == 0) {
         maxSum = max(maxSum, calcDigitSum(i));
         maxSum = max(maxSum,calcDigitSum(n/i));
      }  
   }
   return maxSum;
}

int main() {
   
   int n = 32;
   cout<<"The divisor with largest sum of digits is "<<largestDigitSumdivisior(n)<<endl;
   return 0;
}

Output

The divisor with largest sum of digits is 8
raja
Published on 25-Jan-2021 04:57:34
Advertisements