在A中加N位数字,以便在C ++中每次加法后都能被B整除?

在这里,我们将看到如何通过在数字A上添加N个数字来生成数字A,并在每个阶段添加新数字时将其与另一个数字B整除。让我们考虑通过在数字A上加4来制作5个数字多余的数字。我们将用7检验可除性。该数字将从8开始。因此,首先将其附加4,因此该数字将为84,可以被7整除。然后将该数字加0,这样它就可以被整除7.如果无法生成该数字,它将返回-1。

算法

addNDigits(a,b,n)

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
   add remaining 0’s with a
   return a.
end

示例

#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;
   }
}

输出结果

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

输出结果

Enter A, B and N: 10 11 5
Unable to get this type of number