ProblemsTemplatesDivision that must not compile
AdvancedTemplates

Division that must not compile

Context

Residue<7> is a field: every non-zero element has an inverse, division works. Residue<6> is not: 2 has no inverse modulo 6, and the Fermat formula in the code just produces a wrong number. Nobody checks this at runtime — the wrong answer goes straight into the calculation. The compiler can refuse such code before it ever runs: a member function of a class template is only instantiated when it is actually called.

Task

In the ring Residue<N>, division is mathematically defined only when N is prime. Right now operator/ compiles for ANY N and silently returns garbage for composite moduli. Make division a compile error for composite N — while +, -, * keep working for every N.

Constraints

  • Residue<6> (or any composite N): +, -, * compile and work
  • Residue<6>: calling / must NOT compile
  • Residue<7> (or any prime N): / compiles and is correct
  • Use a compile-time check (static_assert with the provided isPrime, or SFINAE) — no runtime checks, no exceptions

Before you code

  • Why is a member function of a class template not compiled until the first call?
  • Why does division by Fermat (a^(N-2)) require N to be prime?
  • Where would a runtime check of N be worse than a compile error?

Tests

  • #1Arithmetic works for a composite modulus
  • #2Division is correct for a prime modulus
  • #3Division by a composite modulus does not compile(expects compile error)

Hints

Hint 1

Members of a class template are instantiated lazily: Residue<6> with +, -, * is fine as long as nobody CALLS operator/. Put the check inside the member.

Hint 2

static_assert(isPrime(N), "...") inside operator/ fires only when that operator is instantiated — exactly the behaviour you want.

Editorresidue-division-guard.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.