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


Here we will see a program, that can check whether a number can be divided into more than one segments with equal sum. Suppose a number is like 74325, then this can be segmented into three parts (7), (4, 3), (2, 5), all are of same um value.

We have to follow these steps to solve this problem.

  • Take the number as string
  • use an array to hold prefix sum of the array
  • Now traversing from second element to last element, and the first segment will be 0 to i-1, whose sum will be placed at prefix_sum[i - 1]
  • Use another variable which traverses from 1 to n, then keep adding the sum.
  • If the sum value is same as the prefix_sum[i – 1] at any stage, then the segment has sum equal to the first.
  • Re initialize the segment sum value as 0, then keep moving the pointer.
  • If at any stage the segment sum is greater than the prefix_sum[i – 1] then break the loop
  • If we reach at the last destination, and if last segment sum is same as the first segment sum, then it can be divided into segments of equal sum.

Example

 Live Demo

#include <iostream>
using namespace std;
bool canBeSegmented(string str) {
   int n = str.length();
   int prefix_sum[n];
   prefix_sum[0] = str[0] - '0';
   for (int i = 1; i < n; i++) {
      prefix_sum[i] = prefix_sum[i - 1] + (str[i] - '0');
   }
   for (int i = 1; i <= n - 1; i++) {
      int sum = prefix_sum[i - 1];
      int prev_sum = 0;
      int it = i;
      bool flag = false;
      while (it < n) {
         prev_sum += str[it] - '0';
         if (prev_sum == sum) {
            prev_sum = 0;
            flag = true;
         } else if (prev_sum > sum) {
            break;
         }
         it++;
      }
      if (prev_sum == 0 && it == n && flag) {
         return true;
      }
   }
   return false;
}
int main() {
   string s = "74325";
   if (canBeSegmented(s))
      cout << "Yes, This can be segmented into more than two segments";
   else
      cout << "No, This can not be segmented into more than two segments";
}

Output

Yes, This can be segmented into more than two segments

Updated on: 22-Oct-2019

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements