Count number of ways to divide a number in parts in C++

C++Server Side ProgrammingProgramming

We are given a positive number N. The goal is to count the number of ways in which the number N can be divided into 3 parts. The parts may or may not be equal. N lies in range [1,5000].

We will do this by using three for loops for 3 parts of the number. Check at the innermost loop that the sum of all three is equal to N. If true, then increment the count of ways.

Let’s understand with examples.

Input − N=5

Output − Number of ways to divide N in 3 parts: 2

Explanation − 5 can be shown as sum of (1,1,3) and (1,2,2)

Input − N=9

Output − Number of ways to divide N in 3 parts: 7

Explanation − 9 can be shown as sum of : (1, 1, 7), (1, 2, 6), (1, 3, 5), (1, 4, 4), (2, 2, 5), (2, 3,4) and (3, 3, 3).

Approach used in the below program is as follows

  • We take an integer N initialized with a value between 1 and 5000.

  • Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts.

  • Take the initial variable count as 0 for the number of ways.

  • Traverse using three for loops for each part of the number.

  • Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n.

  • Check if the sum of i, j and k is equal to n . If true then increment count.

  • At the end of all loops count will have a total number of ways to divide n in three parts.

  • Return the count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int divideN(int n){
   int count = 0;
   for (int i = 1; i < n; i++){
      for (int j = i ; j < n; j++){
         for (int k = j; k < n; k++){
            int sum=i+j+k;
            if(sum==n)
               { count++; }
         }
      }
   }
   return count;
}
int main(){
   int N=500;
   cout <<endl<< "Number of ways to divide N in 3 parts : "<<divideN(N);
   return 0;
}

Output

If we run the above code it will generate the following output −

Number of ways to divide N in 3 parts: 20833
raja
Published on 31-Oct-2020 10:00:45
Advertisements