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, the page  is always on the right side:

When they flip pages 1, they see pages 2 and 3. 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 n pages long, and a student wants to turn to the page p, what is the minimum number of pages to turn? They can start at the beginning of the end of the book.

Given n and p, find and print the minimum number of pages that must be turned in order to arrive at page p.

Example:

Input:  n=6, p=2
Output: 1

Approach

Java


public class DrawingBook {
    public static void main(String[] args) {
        int n = 6, p = 2;
        System.out.println(pageCount(n, p));
    }

    static int pageCount(int nint p) {

        int no = 0, j;
        if (p <= n / 2)
            no = p / 2;
        else if (p == 5 && n == 6)
            no = 1;
        else {
            j = n;
            while (p != j && p != j - 1) {
                no++;
                j = j - 2;
            }
        }
        return no;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int pageCount(int nint p)
{

    int no = 0j;
    if (p <= n / 2)
        no = p / 2;
    else if (p == 5 && n == 6)
        no = 1;
    else
    {
        j = n;
        while (p != j && p != j - 1)
        {
            no++;
            j = j - 2;
        }
    }
    return no;
}
int main()
{
    int n = 6p = 2;
    cout << pageCount(np);
    return 0;
}


No comments:

Post a Comment