DISCLAIMER: This only works with LuaTeX and only with integers.
If you want to work with arbitrary-precision integers, a pure Lua module which handles very well with otherwise difficult cases is lua-nums
. You need to download bn.lua
and put it in the same folder as your main file.
I've avoided parsing, but you could look at LPEG for more advanced examples. For the moment, basic operations (+
, -
, *
, /
, ^
, //
, %
) and binary operators (&
, |
, >>
, <<
, ~
, |
) should work, although passing special characters to Lua is kinda a pain. There's a trade-off between cumbersome typing and speed of operations as lua-nums
runs smoothly.
\documentclass{article}
%\usepackage{geometry}
%\geometry{paperwidth=100mm,paperheight=85mm,margin=2em}
\usepackage{luacode}
\begin{luacode*}
userdata = userdata or {}
--bn.lua should be in the same folder as \jobname.tex
userdata.bn = require"bn"
userdata.evaluatebn = function(s)
return load("return ".. s:gsub("%d+", "userdata.bn(%1)"))()
end
\end{luacode*}
\newcommand{\evaluatebn}[1]{\directlua{tex.sprint(tostring(userdata.evaluatebn("#1")))}}
\begin{document}
\section{Rationale}
In Spanish and English (long scale), a trillion stands for $10^{18}$: \evaluatebn{10^18}.
%Integer division, so // and / are interchangeable
25\% of 80 trillion (long scale) is \evaluatebn{80*10^18//4}
25\% of 80 trillion (short scale) is \evaluatebn{80*10^12//4}
\section{Some other examples}
\begin{itemize}
\item $2^{70} = \evaluatebn{1 << 70}$
% \string& instead of Lua's &
\item $47542121789123 = 4\times\evaluatebn{(47542121789123 >> 2)} + \evaluatebn{(47542121789123 \string& 3)}$
\item $15! = \evaluatebn{1*2*3*4*5*6*7*8*9*10*11*12*13*14*15}$
% \csstring\% instead of Lua's %
\item $47542121789\% 4787973 = \evaluatebn{(47542121789 \csstring\% 4787973)}$
\end{itemize}
\end{document}

sagetex
on this site for examples. – DJP Dec 5 '20 at 1:34