Minimum number of page turns to get to a desired page using C++.

C++Server Side ProgrammingProgramming

Problem statement

Given a book of N pages, the task is to calculate the minimum number of page turns to get to a give desired page K.

  • we can either start turning pages from the front side of the book (i.e from page 1) or from the backside of the book (i.e page number N).

  • Each page has two sides, front and back, except the first page, which has only backside and the last page which may only have backside depending on the number of pages of the book.

If N = 5 and K = 4 then we have to turn minimum 1 page −

  • If we start page-turning from front then 2 turns are required (1) -> (2, 3) -> (4,5)

  • If we start page-turning from the back, (4, 5) 1 turn is required page turned = 1

So, a Minimum number of pages turned = 1.

Algorithm

Use below formula to calculate final result −

1. If K is even, front distance = (K – 0)/2 and back distance = (N – 1 – K)/2
2. If K is odd, front distance = (K – 1)/2 and back distance = (N – K)/2

Example

#include <iostream>
#include <algorithm>
using namespace std;
int getMinPageTurns(int n, int k){
   if (n % 2 == 0) {
      ++n;
   }
   return min((k + 1) / 2, (n -k + 1) / 2);
}
int main(){
   int n = 5, k = 4;
   cout << "Required page turns = " << getMinPageTurns(n, k) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Required page turns = 1
raja
Published on 31-Oct-2019 07:26:43
Advertisements