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


Given a, b and n. And we have to consider the following conditions and find the optimal solution to add n digits to a such that it is divisible by b after every iteration.

  • Add a digit to in such way that after adding it, is divisible by b.

  • Print the smallest value of possible after n iterations of step1.

  • Print fail if the operation fails.

check divisibility after every digit addition.

Input

a=5 b=4 n=4

Output

52000

Explanation

The first digit to be added from 0 to 9, if none of the digits make a divisible by b then the answer is -1 which means the if n digits are added in a. a never be divided by b . else add the first digit that satisfies the condition and then add 0 after that (n-1) times because if a is divisible by b then a*10, a*100, … will also be divisible by b.

Example

#include <iostream>
using namespace std;
int main() {
   int a = 5, b = 4, n = 4;
   int num = a;
   for (int i = 0; i <= 9; i++) {
      int temp = a * 10 + i;
      if (temp % b == 0) {
         a = temp;
         break;
      }
   }
   if (num == a) {
      a = -1;
   }
   for (int j = 0; j < n - 1; j++) {
      a *= 10;
   }
   if(a>-1) {
      cout <<a;
   } else {
      cout <<”fail”;
   }
   return 0;
}
raja
Published on 16-Aug-2019 08:38:53
Advertisements