
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum number of page turns to get to a desired page using C++.
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
- Related Articles
- How to get the total number of checkboxes in a page using Selenium?
- How to get the total number of radio buttons on a page using Selenium?
- How to get content of entire page using Selenium?
- How to get the protocol and page path of the current web page in JavaScript?
- How to print a page using JavaScript?
- Get page title with Selenium WebDriver using Java.
- How to make a page redirect using jQuery?
- How to get page source as it is in browser using selenium?
- How to make page links in HTML Page?
- How to get innerHTML of whole page in selenium driver?
- How to set the minimum number of lines for an element that must be left at the bottom of a page when a page break occurs inside an element with JavaScript?
- How to load a page in div using jQuery?
- How to create a common error page using JSP?
- How to create a "Coming Soon" page using JavaScript?
- How do you get selenium to recognize that a page loaded?
