# Add N digits to A such that it is divisible by B after each addition in C++?

C++Server Side ProgrammingProgramming

Here we will see how to generate a number A by adding N digits with it, and while adding new digits in each stage it will be divisible by another number B. Let us consider we are going to make a 5-digit number by adding 4 extra digits with it. We will check the divisibility by 7. The number will start from 8. So at first it will append 4 with it, so the number will be 84, that is divisible by 7. Then add 0 with the number so it will remain divisible by 7. If the number cannot be generated, it will return -1.

## Algorithm

begin
num := a
for all number x from 0 to 9, do
temp := a * 10 + x
if temp mod b is 0, then
a := temp
break
end if
done
if num = a, then
return -1
end if
return a.
end

## Example

Live Demo

#include<iostream>
using namespace std;
int add_n_digits(int a, int b, int n) {
int num = a;
for (int i = 0; i <= 9; i++) { //test by adding all digits (0-9)
int tmp = a * 10 + i;
if (tmp % b == 0) {
a = tmp; //update a after adding
break;
}
}
if (num == a) //if no digit is added, return -1
return -1;
for (int j = 0; j < n - 1; j++) //after getting divisible number, add 0s
a *= 10;
return a;
}
main() {
int a, b, n;
cout << "Enter A, B and N: ";
cin >> a >> b >> n;
int res = add_n_digits(a, b, n);
if(res == -1) {
cout << "Unable to get this type of number";
} else {
cout << "Result is " << res;
}
}

## Output

Enter A, B and N: 8 7 4
Result is 84000

## Output

Enter A, B and N: 10 11 5
Unable to get this type of number
Published on 24-Jul-2019 12:54:28