Translate with a page table

Use a page table to turn virtual addresses into physical addresses, or report a page fault.

What to build

A program that translates a list of virtual addresses.

Requirements

  • The page table lists the pages that are in memory, each with its frame number. Any other page is not in memory.
  • For each address print its physical address (frame × page size + offset) as a decimal number, or page fault if its page is not in the table.

Input

A line with the page size, a line with m, then m lines page frame, a line with n, then n addresses, one per line.

Output

n lines.

Constraints

1 ≤ page size ≤ 65536; 0 ≤ m ≤ 50; 1 ≤ n ≤ 100; addresses are from 0 to 10⁷.

Example

Input:

256
3
0 5
1 2
3 7
4
16
511
768
512

Output:

1296
767
1792
page fault

Why it works

The hardware replaces the page number with the frame number and keeps the offset. A page that has no entry causes a fault for the operating system to handle.

Examples

Example 1 · Input
256
3
0 5
1 2
3 7
4
16
511
768
512
Expected output
1296
767
1792
page fault
Example 2 · Input
4096
1
2 1
2
8192
0
Expected output
4096
page fault

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Read the page table into a dictionary from page to frame.

Hint 2

physical = frame * page_size + offset.

Solution

Show one correct solution (try it yourself first)
size = int(input())
m = int(input())
table = {}
for _ in range(m):
    p, f = map(int, input().split())
    table[p] = f
n = int(input())
for _ in range(n):
    a = int(input())
    p, o = divmod(a, size)
    print(table[p] * size + o if p in table else "page fault")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Virtual memory, page tables and the TLB →