Maximum number of pieces in N cuts in C++


Given the task is to calculate the maximum number of square or rectangle pieces of equal size that can be obtained by cutting a given square piece in total N number of cuts horizontally or vertically.

Let’s now understand what we have to do using an example −

Input − N=8

Output − 25

Explanation − When N=8, the number of vertical cuts = 4 and the number of horizontal cuts = 4.

Total pieces = 25

12345
678910
1112131415
1617181920
2122232425

Input − 7

Output − 20

12345
678910
1112131415
1617181920

Approach used in the below program as follows

  • If N is the number of cuts and we have to maximize the resultant pieces then equal number of horizontal and vertical cuts have to be made.

    If N is even then there will be equal horizontal and vertical cuts else if N is odd, then the horizontal cuts will be 1 more than the vertical cuts or vice versa.

    Therefore, the number of horizontal = N/2 and vertical cuts = N-H.

  • In function MaxPieces() initialize a variable H =N/2 of type int to store the number of Horizontal cuts.

  • Initialize another variable V=N-H of type int to store the number of vertical cuts.

  • Final number of pieces = (Horizonal Rows)*(Vertical rows) = (H+1)*(V+1)

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int MaxPieces(int N){
   //H is the number of horizontal cuts
   int H = N / 2;
   //V is the number of vertical cuts
   int V = N-H;
   // maximum number of pieces = (H+1)*(V+1)
   return ((H + 1) * (V + 1));
}
//Main function
int main(){
   //Number of cuts
   int N = 7;
   cout << "Max pieces = "<<MaxPieces(N);
   return 0;
}

Output

If we run the above code we will get the following output −

20

Updated on: 17-Aug-2020

500 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements