- Drawing Book
-
- A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page is always on the right side:
-
- image
-
- When they flip page , they see pages and . Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is pages long, and a student wants to turn to page , what is the minimum number of pages to turn? They can start at the beginning or the end of the book.
-
- Given and , find and print the minimum number of pages that must be turned in order to arrive at page .
-
-
-
-
-
- public static int pageCount(int n, int p) {
-
- //count how many steps are required to generate 1 to n pages
- int step=n/2+1;
- // checking from front
- int front=Integer.MAX_VALUE;
- // checking from last
- int last=Integer.MAX_VALUE;
- int j=step;
- int i=1;
- int k=0;
- int l=0;
- while(i<=step)
- {
- int firstF=2*(i-1);
- int secondF=2*i-1;
- if(firstF==p||secondF==p)
- {
- front=(int)Math.min(front,k);
- }
- k++;
-
-
-
- int firstL=2*(j-1);
- int secondL=2*j-1;
- if(firstL==p||secondL==p)
- {
- last=(int)Math.min(last,l);
- }
- l++;
- j--;
- i++;
- }
-
- int ans=Math.min(front,last);
- return ans;
-
- }