[texhax] Beginner in TEX MACRO to compute functions

Heiko Oberdiek heiko.oberdiek at googlemail.com
Mon Apr 9 02:29:04 CEST 2012


On Sat, Apr 07, 2012 at 12:29:51AM +0200, Jon Abraham wrote:

> I have the following questions as exercise of Concept of Programming
> language class. This is totally new for me and don't have too much time to
> be familiar with (highest 8/10 hours). Can anyone help me to find any
> source where I can get some quick learning material as a starter and can
> solve the problems within the time frame..

* Victor Eijkhout: "TeX by Topic", chapter 11 "Macros".
  http://mirror.ctan.org/info/texbytopic/

> Write a Macro in TEX that compute the function \fib{m} All fibonacci
> numbers from 1 to m (m < 40).

A trivial solution for 0 <= m <= 46 (the result is in the valid
range of a TeX number). 

%%% test.tex %%%
% catcode settings in case that iniTeX is used
\catcode`\{=1 
\catcode`\}=2 
\catcode`\#=6 

% \fib{<m>} for 0 <= <m> <= 46
% Because of the limitation the supported values can
% already be calculated. That simplifies the implementation.
% If a fibonacci number is used later in counter assignments,
% the the limitation for the value is 2^{31}-1, that means
% m <= 46.
\def\fib#1{%
  \ifcase#1 %   
      0% 0
  \or 1% 1
  \or 1% 2
  \or 2% 3
  \or 3% 4
  \or 5% 5
  \or 8% 6
  \or 13% 7
  \or 21% 8
  \or 34% 9
  \or 55% 10
  \or 89% 11
  \or 144% 12
  \or 233% 13
  \or 377% 14
  \or 610% 15
  \or 987% 16
  \or 1597% 17
  \or 2584% 18
  \or 4181% 19
  \or 6765% 20
  \or 10946% 21
  \or 17711% 22
  \or 28657% 23
  \or 46368% 24
  \or 75025% 25
  \or 121393% 26
  \or 196418% 27
  \or 317811% 28
  \or 514229% 29
  \or 832.040% 30
  \or 1346269% 31
  \or 2178309% 32
  \or 3524578% 33
  \or 5702887% 34
  \or 9227465% 35
  \or 14930352% 36
  \or 24157817% 37
  \or 39088169% 38
  \or 63245986% 39
  \or 102334155% 40
  \or 165580141% 41
  \or 267914296% 42
  \or 433494437% 43
  \or 701408733% 44
  \or 1134903170% 45
  \or 1836311903% 46
  \else
    \errmessage{Macro fib: number too large}%
  \fi
}

% print on terminal:
\message{*** fib(39) = \fib{39} ***}

% end for LaTeX and plain TeX
\csname @@end\endcsname\end
%%% test.tex %%%

The example can be run with iniTeX, plain TeX, LaTeX, e.g.:

tex --ini test
latex test


Also I have written a package `fibnum' that implements an expandable
\fibnum{<n>} where <n> is an integer in the range [-(2^{31}-1), 2^{31}-1].
Until some time after I have managed my bundle update, it's available at
  http://dl.dropbox.com/u/71873949/tex/fibnum.pdf
The file `fibnum.dtx' is embedded as file attachment.
The package `fibnum.sty' is unpacked by plain TeX (or iniTeX, but not LaTeX):
  tex fibnum.dtx

Yours sincerely
  Heiko Oberdiek


More information about the texhax mailing list