Partition a number into two divisble parts

Given a number (as string) and two integers a and b, divide the string in two non-empty parts such that the first part is divisible by a and second part is divisible by b. If string can not be divided into two non-empty parts, output “NO”, else print “YES” with the two parts.

Examples:

Input  : str = "123", a = 12, b = 3
Output : YES
         12, 3
"12" is divisible by a and "3" is 
divisible by b. 

Input  : str = "1200", a = 4, b = 3
Output : YES
         12, 00

Input  : str = "125", a = 12, b = 3
Output : NO

A simple solution is to one by one partition array around all points. For every partition, check if left and right of it are divisible by a and b respectively. If yes, print the left and right parts and return.



An efficient solution is to do some preprocessing and save the division modulo by ‘a’ by scanning the string from left to right and division modulo by ‘b’ from right to left.

If we know the remainder of prefix from 0 to i, when divided by a, then we compute remainder of prefix from 0 to i+1 using below formula.
lr[i+1] = (lr[i]*10 + str[i] -‘0’)%a.

Same way, modulo by b can be found by scanning from right to left. We create another rl[] to store remainders with b from right to left.

Once we have precomputed two remainders, we can easily find the point that partition string in two parts.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to check if a string can be splitted
// into two strings such that one is divisible by 'a'
// and other is divisible by 'b'.
#include <bits/stdc++.h>
using namespace std;
  
// Finds if it is possible to paritiion str
// into two parts such that first part is
// divisible by a and second part is divisible
// by b.
void findDivision(string &str, int a, int b)
{
    int len = str.length();
  
    // Create an array of size len+1 and initialize
    // it with 0.
    // Store remainders from left to right when
    // divided by 'a'
    vector<int> lr(len+1, 0);
    lr[0] = (str[0] - '0')%a;
    for (int i=1; i<len; i++)
        lr[i] = ((lr[i-1]*10)%a + (str[i]-'0'))%a;
  
    // Compute remainders from right to left when
    // divided by 'b'
    vector<int> rl(len+1, 0);
    rl[len-1] = (str[len-1] - '0')%b;
    int power10 = 10;
    for (int i= len-2; i>=0; i--)
    {
        rl[i] = (rl[i+1] + (str[i]-'0')*power10)%b;
        power10 = (power10 * 10) % b;
    }
  
    // Find a point that can partition a number
    for (int i=0; i<len-1; i++)
    {
        // If split is not possible at this point
        if (lr[i] != 0)
            continue;
  
        // We can split at i if one of the following
        // two is true.
        // a) All charactes after str[i] are 0
        // b) String after str[i] is divisible by b, i.e.,
        //    str[i+1..n-1] is divisible by b.
        if (rl[i+1] == 0)
        {
            cout << "YES\n";
            for (int k=0; k<=i; k++)
                cout << str[k];
  
            cout << ", ";
  
            for (int k=i+1; k<len; k++)
                cout << str[k];
            return;
        }
    }
  
    cout << "NO\n";
}
  
// Driver code
int main()
{
    string str = "123";
    int a = 12, b = 3;
    findDivision(str, a, b);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if a string can be splitted 
// into two strings such that one is divisible by 'a' 
// and other is divisible by 'b'. 
class GFG
{
      
// Finds if it is possible to paritiion str 
// into two parts such that first part is 
// divisible by a and second part is divisible 
// by b. 
static void findDivision(String str, int a, int b) 
    int len = str.length(); 
  
    // Create an array of size len+1 and initialize 
    // it with 0. 
    // Store remainders from left to right when 
    // divided by 'a' 
    int[] lr = new int[len + 1]; 
      
    lr[0] = ((int)str.charAt(0) - (int)'0')%a; 
    for (int i = 1; i < len; i++) 
        lr[i] = ((lr[i - 1] * 10) % a + 
                ((int)str.charAt(i)-(int)'0')) % a; 
  
    // Compute remainders from right to left when 
    // divided by 'b' 
    int[] rl = new int[len + 1]; 
    rl[len - 1] = ((int)str.charAt(len - 1) -
                            (int)'0') % b; 
    int power10 = 10
    for (int i= len - 2; i >= 0; i--) 
    
        rl[i] = (rl[i + 1] + ((int)str.charAt(i) - 
                        (int)'0') * power10) % b; 
        power10 = (power10 * 10) % b; 
    
  
    // Find a point that can partition a number 
    for (int i = 0; i < len - 1; i++) 
    
        // If split is not possible at this point 
        if (lr[i] != 0
            continue
  
        // We can split at i if one of the following 
        // two is true. 
        // a) All charactes after str.charAt(i] are 0 
        // b) String after str.charAt(i] is divisible by b, i.e., 
        // str.charAt(i+1..n-1] is divisible by b. 
        if (rl[i + 1] == 0
        
            System.out.println("YES"); 
            for (int k = 0; k <= i; k++) 
                System.out.print(str.charAt(k)); 
  
            System.out.print(", "); 
  
            for (int k = i + 1; k < len; k++) 
                System.out.print(str.charAt(k)); 
            return
        
    
    System.out.println("NO"); 
  
// Driver code 
public static void main (String[] args) 
{
    String str = "123"
    int a = 12, b = 3
    findDivision(str, a, b); 
}
  
// This code is contributed by mits

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to check if a can be splitted
# into two strings such that one is divisible by 'a'
# and other is divisible by 'b'.
  
# Finds if it is possible to paritiion str
# into two parts such that first part is
# divisible by a and second part is divisible
# by b.
def findDivision(str, a, b):
    lenn = len(str)
      
    # Create an array of size lenn+1 and 
    # initialize it with 0.
    # Store remainders from left to right 
    # when divided by 'a'
    lr = [0] * (lenn + 1)
    lr[0] = (int(str[0]))%a
    for i in range(1, lenn):
        lr[i] = ((lr[i - 1] * 10) % a + \
                     int(str[i])) % a
                       
    # Compute remainders from right to left 
    # when divided by 'b'
    rl = [0] * (lenn + 1)
    rl[lenn - 1] = int(str[lenn - 1]) % b
    power10 = 10
    for i in range(lenn - 2, -1, -1):
        rl[i] = (rl[i + 1] + int(str[i]) * power10) % b
        power10 = (power10 * 10) % b
          
    # Find a pothat can partition a number
    for i in range(0, lenn - 1):
          
        # If split is not possible at this point
        if (lr[i] != 0):
            continue
              
        # We can split at i if one of the following
        # two is true.
        # a) All charactes after str[i] are 0
        # b) after str[i] is divisible by b, i.e.,
        # str[i+1..n-1] is divisible by b.
        if (rl[i + 1] == 0):
            print("YES")
            for k in range(0, i + 1):
                print(str[k], end = "")
              
            print(",", end = " ")
              
            for i in range(i + 1, lenn):
                print(str[k], end = "")
                return
      
    print("NO")
  
# Driver code
str = "123"
a, b = 12, 3
findDivision(str, a, b)
  
# This code is contributed by SHUBHAMSINGH10

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to check if a string can be splitted 
// into two strings such that one is divisible by 'a' 
// and other is divisible by 'b'. 
using System;
  
class GFG
{
      
// Finds if it is possible to paritiion str 
// into two parts such that first part is 
// divisible by a and second part is divisible 
// by b. 
static void findDivision(string str, int a, int b) 
    int len = str.Length; 
  
    // Create an array of size len+1 and initialize 
    // it with 0. 
    // Store remainders from left to right when 
    // divided by 'a' 
    int[] lr = new int[len + 1]; 
    lr[0] = ((int)str[0] - (int)'0')%a;
      
    for (int i = 1; i < len; i++) 
        lr[i] = ((lr[i - 1] * 10) % a + 
                ((int)str[i] - (int)'0')) % a; 
  
    // Compute remainders from right to left when 
    // divided by 'b' 
    int[] rl = new int[len + 1]; 
    rl[len - 1] = ((int)str[len - 1] - (int)'0') % b; 
      
    int power10 = 10; 
    for (int i= len - 2; i >= 0; i--) 
    
        rl[i] = (rl[i + 1] + ((int)str[i] - 
                (int)'0') * power10) % b; 
        power10 = (power10 * 10) % b; 
    
  
    // Find a point that can partition a number 
    for (int i = 0; i < len - 1; i++) 
    
        // If split is not possible at this point 
        if (lr[i] != 0) 
            continue
  
        // We can split at i if one of the following 
        // two is true. 
        // a) All charactes after str[i] are 0 
        // b) String after str[i] is divisible by b, i.e., 
        // str[i+1..n-1] is divisible by b. 
        if (rl[i + 1] == 0) 
        
            Console.WriteLine("YES"); 
            for (int k = 0; k <= i; k++) 
                Console.Write(str[k]); 
  
            Console.Write(", "); 
  
            for (int k = i + 1; k < len; k++) 
                Console.Write(str[k]); 
            return
        
    
    Console.WriteLine("NO"); 
  
// Driver code 
static void Main() 
    string str = "123"
    int a = 12, b = 3; 
    findDivision(str, a, b); 
}
  
// This code is contributed by mits

chevron_right



Output :

YES
12, 3

Time Complexity : O(len) where len is length of input number string.

This article is contributed by Ekta Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.about the topic discussed above



My Personal Notes arrow_drop_up

Recommended Posts: