Determine page number for question based on count of questions and number of questions per page

60 Views Asked by At

I'm trying to build a simple quiz, and I want to split up the questions into pages. However, the number of questions and pages can change based on a few parameters, most important is a variable number of questions per page.

For example. I have 10 questions, and I would like 3 questions per page. If I know this, I know that I would need 4 pages, using something like (excuse my pseudo code) Math.Ceiling(10/3) = 4.

So given all of this information, if I am looping through each question, and I know it's question number, how do I determine what page it belongs to? In a previous iteration I was doing it another way where I would give a page and then ask what questions I needed with something like:

question_start = ((page * questions_per_page) - questions_per_page) + 1
question_end = question_start + questions_per_page - 1

So given all of this, I imagine I'm being somewhat dense today, but how do I determine what page a given question lands on given all of the information I have (total questions, questions per page)?

2

There are 2 best solutions below

2
On BEST ANSWER

Assuming $P$ and $Q$ start at 1, you have

$$P = 1 + \left\lfloor\frac{Q-1}{QPP}\right\rfloor$$

0
On

$\left\lfloor\frac {q-1}p \right\rfloor+1$ where $q$ is the question number and $p$ is the number of questions per page should do the trick.