在 C++ 中,如何向数字 A 添加 N 位数字,使得每次添加后 A 都能被 B 整除?
在这里,我们将了解如何通过向数字 A 添加 N 位数字来生成一个新的数字,并且在每个阶段添加新数字时,它都将能够被另一个数字 B 整除。让我们考虑一下,我们要通过向一个数字添加 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP