# Find minimum possible digit sum after adding a number d in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers n and d. Our task is to Find the minimum possible digit sum after adding a number d.

Problem Description − we need to minimise the digits sum by adding kth multiple of d to n.

Let’s take an example to understand the problem,

## Input

n = 5230, d = 54

## Output

1

## Explanation

The number will be 5230 + (2*54) = 5338

## Solution Approach

A simple approach to solve the problem would be to check all multiples of d from 1 to 8, as at 9th multiple the sum of digits will repeat. This is based on modulo 9, which will return the digits sum. So, a+d*(9k+l) modulo 9 is equivalent to a+d*l modulo 9. Hence we will check for all multiples of l*d from 1 to 8, and return the minimum found.

One advancement in the program can be made using the fact that digit sum will never be less than 1, so if we have digit sum = 1, we will return it.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
int calcDigitSum(int n) {
int i = n % 9;
if (i == 0)
return 9;
else
return i;
}
int findMinDigitSum(int n, int d) {
int minSum = 10;
int number;
for (int i = 1; i < 9; i++) {
number = (n + i * d);
minSum = min(minSum, calcDigitSum(number));
if(minSum == 1)
return minSum;
}
return minSum;
}
int main() {
int n = 5230, d = 54;
cout<<"The minimum possible digitsum after adding the number is "<<findMinDigitSum(n, d);
return 0;
}

## Output

The minimum possible digitsum after adding the number is 1