# How Many Ways Can You Tile a Chessboard With Dominoes?

# How Many Ways Can You Tile a Chessboard With Dominoes?

### When calculating the number of possible combinations, there's some math and, in turn, some code that can help you handle big figures.

Join the DZone community and get the full member experience.

Join For FreeHortonworks Sandbox for HDP and HDF is your chance to get started on learning, developing, testing and trying out new features. Each download comes preconfigured with interactive tutorials, sample data and developments from the Apache community.

Suppose you have an *n* by *m* chessboard. How many ways can you cover the chessboard with dominoes?

It turns out there’s a remarkable closed-form solution:

Here are some questions you may have.

*But what if n and m are both odd? You can’t tile such a board with dominoes.*

Yes, in that case, the formula evaluates to zero.

*Do you need an absolute value somewhere? Or a floor or ceiling?*

No. It looks like the double product could be a general complex number, but it’s real. In fact, it’s always the square of an integer.

*Does it work numerically?*

Apparently so. If you evaluated the product in a package that could symbolically manipulate the cosines, the result would be exact. In floating point, it cannot be, but at least in my experiments, the result is correct when rounded to the nearest integer. For example, there are 12,988,816 ways to tile a standard 8 by 8 chessboard with dominoes, and the following Python script returns 12988816.0. For sufficiently large arguments the result will not always round to the correct answer, but for moderate-sized arguments, it should.

```
from numpy import pi, cos, sqrt
def num_tilings(m, n):
prod = 1
for k in range(1, m+1):
for l in range(1, n+1):
prod *= 2*cos(pi*k/(m+1)) + 2j*cos(pi*l/(n+1))
return sqrt(abs(prod))
print(num_tilings(8,8))
```

*The code looks wrong. Shouldn’t the ranges go up to m and n?*

No, Python ranges are half-open intervals. `range(a, b)`

goes from `a`

to `b-1`

. That looks unnecessarily complicated, but it makes some things easier.

*You said that there was no need for absolute values, but you code has one.*

Yes, because while, in theory, the imaginary part will be exactly zero, in floating point arithmetic the imaginary part might be small but not zero.

*Where did you find this formula?*

Thirty-three Miniatures: Mathematical and Algorithmic Applications of Linear Algebra

Hortonworks Sandbox for HDP and HDF is your chance to get started on learning, developing, testing and trying out new features. Each download comes preconfigured with interactive tutorials, sample data and developments from the Apache community.

Published at DZone with permission of John Cook , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

## {{ parent.title || parent.header.title}}

## {{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}