How do I calculate n modulo 3 in LaTeX?

There are several nice answers using different packages. I'd like to note that TeX uses integer arithmetics, so it is easy to program the standard formula a-(a/b)*b, where / means integer division.

Plain TeX solution:

\newcount\tmpcnta
\def\modulo#1#2{\tmpcnta=#1
        \divide\tmpcnta by #2
        \multiply\tmpcnta by #2
        \multiply\tmpcnta by -1
        \advance\tmpcnta by #1\relax
        \the\tmpcnta}
\modulo{17}{3}
\modulo{19}{3}
\bye

LaTeX solution:

\documentclass{article} 
\makeatletter
\newcommand\modulo[2]{\@tempcnta=#1
        \divide\@tempcnta by #2
        \multiply\@tempcnta by #2
        \multiply\@tempcnta by -1
        \advance\@tempcnta by #1\relax
        \the\@tempcnta}
\makeatother
\begin{document} 
\modulo{17}{3}
\modulo{19}{3}
\end{document}

You can also use \intcalcMod from the intcalc package:

\documentclass{article}
\usepackage{amsmath}
\usepackage{ifthen}
\usepackage{intcalc}

\newcounter{mycount}
\newcommand\Nmodiii[1]{%
\setcounter{mycount}{0}\whiledo{\value{mycount}<#1}
  {$\themycount\pmod 3=\intcalcMod{\value{mycount}}{3}$\\\stepcounter{mycount}}
}
\begin{document}

\noindent A little example: $8\pmod 3=\intcalcMod{8}{3}$

\noindent And a little loop:\\
\Nmodiii{20}

\end{document}

enter image description here

The code that appears in the link posted in a comment, there are some spurious blank spaces producing an undesired indentation of the first line; here's a corrected version:

\documentclass{article}
\usepackage{ifthen}
\usepackage{forloop}
\usepackage{fmtcount}
\usepackage{intcalc}
\usepackage{multicol}

\begin{document}
\begin{multicols}{2}
\newcounter{i}
\noindent\forloop{i}{1}{\value{i} < 101}{%
    \ifthenelse{\equal{\intcalcMod{\value{i}}{15}}{0}}{
        FizzBuzz
    }{%
        \ifthenelse{\equal{\intcalcMod{\value{i}}{3}}{0}}{
            Fizz
        }{%
            \ifthenelse{\equal{\intcalcMod{\value{i}}{5}}{0}}{
                Buzz
            }{%
                \thei
            }
        }
    }\\
}
\end{multicols}
\end{document}

The fp package is small and provides the functionality to do quite complex arithmetic. In the minimal example below the macro \modulo{<a>}{<b>} stores the result of <a> mod <b> in the macro \result, which is then directly printed:

enter image description here

\documentclass{article}
\usepackage[nomessages]{fp}% http://ctan.org/pkg/fp
\newcommand{\modulo}[2]{%
  \FPeval{\result}{trunc(#1-(#2*trunc(#1/#2,0)),0)}\result%
}
\begin{document}
Some modular arithmetic:
\begin{itemize}
  \item $512 \pmod{7}=\modulo{512}{7}$
  \item $6 \pmod{4}=\modulo{6}{4}$
  \item $15 \pmod{4}=\modulo{15}{4}$
  \item $1234567 \pmod{3}=\modulo{1234567}{3}$
\end{itemize}
\end{document}

Since the result is stored in \result, it can be used later in the text as well, until another execution of \modulo will overwrite \result.

Similar functionality in terms of mathematical functions is provided with pgf as well.

Tags:

Calculations