[OS X TeX] Macro for multiplying numbers

Ross Moore ross at ics.mq.edu.au
Sun Mar 6 04:44:22 CET 2005


Hello Kapila,

On 06/03/2005, at 12:17 PM, Kapila Rohan Attele wrote:

>
> I made  a macro for multiplying integers
>
> \def\mul#1#2{\newcounter{a}\newcounter{b}\setcounter{a}{#1}\setcounter{ 
> b}{#2} \multiply \value{a} by \value{b} \the\value{a}}

Nice thought, but doomed to failure with this approach.

By having \newcounter  in the expansion,
you will allocate two new registers *every* time
you call this macro.

If you use it a lot, then eventually you'll run out
of count registers, and TeX will just die on you,
accompanied by a seemingly meaningless error message.


Better is to allocate the registers once at the beginning,
then use the same registers for each call to your macro.

This is actually trickier than it sounds, since when you
nest calls to \mul, as you want to do below, then you need
to make sure that the registers actually contain the correct
numbers -- not values left behind from a previous invocation.
This is non-trivial computer programming, concerning efficiency
and proper memory-management --- certainly not COMP101.


But why are you doing this anyway ?
Doesn't LaTeX's {calc} package already give you ways to do this?

If you are doing it "out-of-curiosity" then you should be
reading the TeXbook instead. Learn something about the TeX
language on which LaTeX is built, and then you'll naturally
learn how to do this kind of thing properly and efficiently.


>
> It can multiply two integers (correctly), but  given 3 to multiply  
> \mul{\mul{4}{5}}{6} it complains
> missing number, treated as zero.

Try
    \expandafter\mul\expandafter{\mul{4}{5}}{6}

Consult "The TeXbook" if you need an explanation of \expandafter .


> How to define a macro that associativity to multiply more than two?


Hope this helps,

	Ross Moore


>
> Rohan Attele
> Chicago State University
>
> --------------------- Info ---------------------
> Mac-TeX Website: http://www.esm.psu.edu/mac-tex/
>           & FAQ: http://latex.yauh.de/faq/
> TeX FAQ: http://www.tex.ac.uk/faq
> List Post: <mailto:MacOSX-TeX at email.esm.psu.edu>
>
>
>
------------------------------------------------------------------------
Ross Moore                                         ross at maths.mq.edu.au
Mathematics Department                             office: E7A-419
Macquarie University                               tel: +61 +2 9850 8955
Sydney, Australia                                  fax: +61 +2 9850 8114
------------------------------------------------------------------------

--------------------- Info ---------------------
Mac-TeX Website: http://www.esm.psu.edu/mac-tex/
           & FAQ: http://latex.yauh.de/faq/
TeX FAQ: http://www.tex.ac.uk/faq
List Post: <mailto:MacOSX-TeX at email.esm.psu.edu>





More information about the macostex-archives mailing list