Bus cycles for unaligned accesses

A memory bus moves w bytes in one cycle, but only from an aligned chunk, that is, from addresses that are multiples of w. An access that crosses a chunk boundary needs more than one cycle.

What to build

A program that counts the bus cycles for each memory access and for the whole list.

Requirements

  • Memory is split into chunks of w bytes: chunk c holds addresses c × w to c × w + w − 1.
  • An access of size bytes starting at address needs one bus cycle for every chunk it touches.
  • Print the cycles of each access on its own line, then total and the sum.

Input

A line with w, a line with n, then n lines, each address size.

Output

n + 1 lines.

Constraints

1 ≤ w ≤ 64; 1 ≤ n ≤ 50; 0 ≤ address ≤ 100000; 1 ≤ size ≤ 200.

Example

Input:

4
4
0 4
2 4
3 1
6 8

Output:

1
2
1
3
total 7

Why it works

The first byte is in chunk address ÷ w and the last in chunk (address + size − 1) ÷ w, both rounded down, so every chunk between them (inclusive) is touched exactly once. An aligned access to one word costs one cycle, which is why compilers align data.

Examples

Example 1 · Input
4
4
0 4
2 4
3 1
6 8
Expected output
1
2
1
3
total 7
Example 2 · Input
8
2
0 8
4 8
Expected output
1
2
total 3

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

Hints

Hint 1

The chunk of an address a is a // w. An access of s bytes touches the chunks from a // w to (a + s - 1) // w.

Hint 2

The number of chunks is last - first + 1, and each chunk needs one bus cycle.

Solution

Show one correct solution (try it yourself first)
w = int(input())
n = int(input())
total = 0
for _ in range(n):
    a, s = map(int, input().split())
    c = (a + s - 1) // w - a // w + 1
    total += c
    print(c)
print("total", total)

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

Lesson: Inside a computer: CPU, memory and buses →