在本教程中,我们将编写一个程序,将数字分为两部分,这些部分可被给定的数字整除。
我们以字符串格式给出了一个数字和另外两个整数。程序应返回是否可以将给定数字分为两部分,以便第一部分可被第一个数字整除,而第二部分可被第二部分整除。
让我们看看解决问题的步骤。
初始化用于除法的数字和两个整数。
迭代数字,直到第一部分可被第一个数字整除。
通过将每个字符转换为数字来形成数字。
被第一个数字整除时,请中断循环。
现在,从下一个索引开始迭代数字的第二部分。
像在第一部分中一样形成数字。
检查第二部分是否可被第二数字整除。
如果第一部分和第二部分分别可被第一数字和第二数字整除,则打印它们,否则打印“不可能”。
让我们看一下代码。
#include <bits/stdc++.h>
using namespace std;
void checkTheDivisabilityOfPrefixAndSuffix(string num, int prefix_dividend, int suffix_dividend) {
int N = num.length();
bool is_prefix_divisable = false, is_suffix_divisable = false;
int index = 0;
int prefix = num[index] - '0';
while (index < N) {
if (prefix % prefix_dividend == 0) {
is_prefix_divisable = true;
break;
}
prefix = prefix * 10 + (num[++index] - '0');
}
int suffix = num[++index] - '0';
while (index < N - 1) {
suffix = suffix * 10 + (num[++index] - '0');
}
cout << suffix << endl;
if (suffix % suffix_dividend == 0) {
is_suffix_divisable = true;
}
if (is_prefix_divisable && is_suffix_divisable) {
cout << prefix << " " << suffix << endl;
}
else {
cout << "Not possible" << endl;
}
}
int main() {
string number = "125333";
int prefix_dividend = 5;
int suffix_dividend = 3;
checkTheDivisabilityOfPrefixAndSuffix(number, prefix_dividend, suffix_dividend);
return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
125 333