Abstract We propose that the stability of dark matter is ensured by a discrete subgroup of the U(1)B–L gauge symmetry, Z2(B–L). We introduce a set of chiral fermions charged under the U(1)B–L in addition to the right-handed neutrinos, and require the anomaly-cancellation conditions associated with the U(1)B–L gauge symmetry. We find that the possible number of fermions and their charges are tightly constrained, and that non-trivial solutions appear when at least five additional chiral fermions are introduced. The Fermat theorem in the number theory plays an important role in this argument. Focusing on one of the solutions, we show that there is indeed a good candidate for dark matter, whose stability is guaranteed by Z2(B–L).