Find N digits number which is divisible by D in C++

C++Server Side ProgrammingProgramming

Suppose we have two numbers N and D. We have to find N digit number, that is divisible by D. If N is 3, and D is 5, then the number can be 500. This can be solved easily. If D is 10 and N is 1, then it will be impossible. We can put D, and suppose the D has m number of digits, then attach N – m number of 0s to make it N digit number and divisible by D.

Example

#include<iostream>
using namespace std;
string nDigitDivByD(int n, int d) {
   string ans = "";
   if (d < 10) {
      ans += to_string(d);
      for (int i = 1; i < n; i++)
      ans += "0";
   }
   else {
      if (n == 1)
         return "Cannot find any number";
      else {
         string temp = to_string(d);
         ans += to_string(d);
         for (int i = 0; i < n-temp.length(); i++)
         ans += "0";
      }
   }
   return ans;
}
int main() {
   int n = 5, d = 15;
   cout << nDigitDivByD(n, d);
}

Output

15000
raja
Published on 01-Nov-2019 15:03:46
Advertisements