Divide number into two parts divisible by given numbers in C++ Program


In this tutorial, we are going to write a program that divides a number into two parts which are divisible by the given numbers.

We have given a number in string format and two other integers. The program should return whether it's possible to divide the given number into two parts such that the first part is divisible by the first number and the second part is divisible by the second part.

Let's see the steps to solve the problem.

  • Initialize the number and two integers for the division.

  • Iterate over the number until the first part is divisible by the first number.

  • Form the number by converting each char into a digit.

  • Break the loop when it's divisible by the first number.

  • Now, iterate from the next index for the second part of the number.

  • Form the number as you do in the first part.

  • Check whether the second part is divisible by the second number or not.

  • If the first and second parts are divisible by first and second numbers respective, then print them else print "Not possible".

Example

Let's see the code.

 Live Demo

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

Output

If you run the above code, then you will get the following result.

125 333

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 28-Jan-2021

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements