Check if a large number can be divided into two or more segments of equal sum

Given a very large Number N. The task is to check if the number can be divided into two or more segments of an equal sum.

Examples:

Input: N = 73452  
Output: Yes
Segments of {7}, {3, 4}, {5, 2} which has equal sum of 7

Input: N = 1248
Output: No

The following steps can be followed to solve the problem:



  1. Since the number can be large, the number is initialized in a string.
  2. Use prefixSum array to store the prefix sum of the array.
  3. Now traverse from second element to last, and the first segment thus will be 0 to i-1, whose sum is Prefixsum[i-1].
  4. Use another pointer which traverses from i to n, and keep adding the sum.
  5. If the sum at any stage is equal to Prefixsum[i-1], then the segment has a sum equal to first.
  6. Reinitialize the segment sum value to 0 and keep moving the pointer.
  7. If at any stage the segment sum exceeds the sum of the first segment, then break, as the division with segment sum as prefixsum[i-1] is not possible.
  8. If the pointer reaches the last number, check if the last segment sum is equal to the first segment sum i.e., prefixsum[i-1], then it can be divided into segments of equal sum.

Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to Check if a large number can be divided 
// into two or more segments of equal sum
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if a number
// can be divided into segments
bool check(string s)
{
    // length of string
    int n = s.length();
  
    // array to store prefix sum
    int Presum[n];
  
    // first index
    Presum[0] = s[0] - '0';
  
    // calculate the prefix
    for (int i = 1; i < n; i++) {
        Presum[i] = Presum[i - 1] + (s[i] - '0');
    }
  
    // iterate for all number from second number
    for (int i = 1; i <= n - 1; i++) {
  
        // sum from 0th index to i-1th index
        int sum = Presum[i - 1];
        int presum = 0;
        int it = i;
  
        // counter turns true when sum
        // is obtained from a segment
        int flag = 0;
  
        // iterate till the last number
        while (it < n) {
            // sum of segments
            presum += s[it] - '0';
  
            // if segment sum is equal
            // to first segment
            if (presum == sum) {
                presum = 0;
                flag = 1;
            }
            // when greater than not possible
            else if (presum > sum) {
                break;
            }
            it++;
        }
  
        // if at the end all values are traversed
        // and all segments have sum equal to first segment
        // then it is possible
        if (presum == 0 && it == n && flag == 1) {
            return true;
        }
    }
    return false;
}
  
// Driver Code
int main()
{
    string s = "73452";
    if (check(s))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to Check if a large number can be divided 
// into two or more segments of equal sum
  
public class GFG {
  
    // Function to check if a number
    // can be divided into segments
    static boolean check(String s)
    {
        // length of string
        int n = s.length();
       
        // array to store prefix sum
        int[] Presum = new int[n];
       
        // first index
        char[] s1 = s.toCharArray();
        Presum[0] = s1[0] - '0';
       
        // calculate the prefix
        for (int i = 1; i < n; i++) {
            Presum[i] = Presum[i - 1] + (s1[i] - '0');
        }
       
        // iterate for all number from second number
        for (int i = 1; i <= n - 1; i++) {
       
            // sum from 0th index to i-1th index
            int sum = Presum[i - 1];
            int presum = 0;
            int it = i;
       
            // counter turns true when sum
            // is obtained from a segment
            int flag = 0;
       
            // iterate till the last number
            while (it < n) {
                // sum of segments
                presum += s1[it] - '0';
       
                // if segment sum is equal
                // to first segment
                if (presum == sum) {
                    presum = 0;
                    flag = 1;
                }
                // when greater than not possible
                else if (presum > sum) {
                    break;
                }
                it++;
            }
       
            // if at the end all values are traversed
            // and all segments have sum equal to first segment
            // then it is possible
            if (presum == 0 && it == n && flag == 1) {
                return true;
            }
        }
        return false;
    }
       
    // Driver Code
    public static void main(String[] args) {
          
        String s = "73452";
        if (check(s))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to Check if a large number can be divided 
# into two or more segments of equal sum
# Function to check if a number 
# can be divided into segments 
def check(s) :
  
    # length of string 
    n = len(s)
  
    # array to store prefix sum 
    Presum = [0] * n
  
    # ord() gives ASCII value
    # first index 
    Presum[0] = ord(s[0]) - ord('0')
  
    # calculate the prefix 
    for i in range(n) :
        Presum[i] = Presum[i - 1] + (ord(s[i]) - ord('0'))
  
    # iterate for all number from second number
    for i in range(n) :
  
        # sum from 0th index to i-1th index 
        sum = Presum[i]
        presum = 0
        it = 1
  
        #  counter turns true when sum 
        # is obtained from a segment
        flag = 0
  
        # iterate till the last number
        while( it < n) :
  
            # sum of segments                         
            presum += ord(s[it]) - ord('0')                             
  
            # if segment sum is equal 
            # to first segment 
            if presum == sum :
                presum = 0
                flag = 1
  
            # when greater than not possible                        
            elif presum > sum :                
                break
                                       
            it += 1
  
        # if at the end all values are traversed 
        # and all segments have sum equal to first segment 
        # then it is possible 
        if presum == 0 and it == n and flag == 1 :
            return True
  
    return False
  
                                       
# Driver Code
if __name__ == "__main__" :
  
    s = "73452"
    if check(s) :
        print("Yes")
    else :
        print("No")
  
# This code is contributed by ANKITRAI1

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to Check if a large
// number can be divided into two
// or more segments of equal sum 
using System;
  
class GFG 
  
    // Function to check if a number 
    // can be divided into segments 
    static bool check(String s) 
    
        // length of string 
        int n = s.Length; 
      
        // array to store prefix sum 
        int[] Presum = new int[n]; 
      
        // first index 
        char[] s1 = s.ToCharArray(); 
        Presum[0] = s1[0] - '0'
      
        // calculate the prefix 
        for (int i = 1; i < n; i++) 
        
            Presum[i] = Presum[i - 1] + (s1[i] - '0'); 
        
      
        // iterate for all number from second number 
        for (int i = 1; i <= n - 1; i++) 
        
      
            // sum from 0th index to i-1th index 
            int sum = Presum[i - 1]; 
            int presum = 0; 
            int it = i; 
      
            // counter turns true when sum 
            // is obtained from a segment 
            int flag = 0; 
      
            // iterate till the last number 
            while (it < n) 
            
                // sum of segments 
                presum += s1[it] - '0'
      
                // if segment sum is equal 
                // to first segment 
                if (presum == sum)
                
                    presum = 0; 
                    flag = 1; 
                
                  
                // when greater than not possible 
                else if (presum > sum)
                
                    break
                
                it++; 
            
      
            // if at the end all values are traversed 
            // and all segments have sum equal to first segment 
            // then it is possible 
            if (presum == 0 && it == n && flag == 1)
            
                return true
            
        
        return false
    
      
    // Driver Code 
    public static void Main(String[] args) 
    
          
        String s = "73452"
        if (check(s)) 
            Console.WriteLine("Yes"); 
        else
            Console.WriteLine("No"); 
    
  
// This code has been contributed by 29AjayKumar

chevron_right


Output:

Yes

Time Complexity: O(N2)
Auxiliary Space: O(N)



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.