# How to return \count value from \def

I wrote a macro which calculate remainder :

\def\remainder#1#2 {%
\newcount\dividendcount
\dividendcount=#1
\newcount\quotientcount
\quotientcount=#1
\divide\quotientcount #2
\multiply\quotientcount #2
\number\dividendcount
}


I want use value from \remainder in other macro. For instance,

\def\othermacro#1 {%
\newcount\tempcount
\tempcount=#1
\divide\tempcount 2
#1 / 2 = \number\tempcount
}


I want write something similar

\begin{document}
\othermacro{\remainder{17}{3}}
\end{document}


And to give next results

2 / 2 = 1


How can I do it?

• The calculator package provides a lot of \def - like macros, containing the result of a computation, the \MODULO macro is also available – user31729 Nov 16 '14 at 9:57

There are a few errors in the definition of \remainder and \othermacro: a \newcount declaration mustn't go inside them, because this would waste a counter at each call. Also a space after #2 is significant and it means that TeX looks for a space after the second argument, raising an error if it doesn't find one and taking as second argument everything that follows the first argument up to this space.

\newcount\dividendcount
\newcount\quotientcount
\def\remainder#1#2{%
\dividendcount=#1
\quotientcount=#1
\divide\quotientcount #2
\multiply\quotientcount #2
\number\dividendcount
}


would be more correct. However this is the instruction for printing the remainder and it's not legal in an assignment like

\tmpcount=\remainder{17}{3}


because TeX wants a <number> after the =, not the instructions to produce one.

If you plan to use \remainder in the context of an assignment like that, you need to make it expandable and this needs \numexpr.

It's quite easy with expl3; I'll assume LaTeX, but it can be done also with Plain TeX.

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\remainder}{mm}
{
\int_eval:n { \int_mod:nn { #1 } { #2 } }
}
\NewDocumentCommand{\othermacro}{m}
{
$% enter math mode #1/2=\int_eval:n { \int_div_truncate:nn { #1 } { 2 } }$ % exit math mode
}
\ExplSyntaxOff

\begin{document}

\othermacro{\remainder{17}{3}}

\end{document}


Here is the Plain TeX version

\input expl3-generic.tex

\ExplSyntaxOn
\cs_new:Npn \remainder #1 #2
{
\int_eval:n { \int_mod:nn { #1 } { #2 } }
}

\cs_new_protected:Npn \othermacro #1
{
$% enter math mode #1/2=\int_eval:n { \int_div_truncate:nn { #1 } { 2 } }$ % exit math mode
}
\ExplSyntaxOff

\othermacro{\remainder{17}{3}}

\bye


Without expl3:

\def\truncdiv#1#2{((#1-(#2-1)/2)/#2)}
\def\remainder#1#2{#1-\truncdiv{#1}{#2}*#2}
\def\eval#1{\number\numexpr#1\relax}

\def\othermacro#1{$\eval{#1}/2=\eval{\truncdiv{#1}{2}}$}

\othermacro{\remainder{17}{3}}

\bye