9

Here is my code to find Greatest Common Divisor of two positive integers.

\documentclass{article}
\usepackage{luacode}

\begin{luacode}
function gcd(a,b)
    if b ~= 0 then
        return gcd(b, a % b)
    else
        return math.abs(a)
    end
end
\end{luacode}
\newcommand\findgcd[2]{\directlua{tex.sprint(gcd(#1,#2))}}

\begin{document}
\findgcd{5,10}
\end{document}

It throws error. The expected output is simply gcd of 5 and 10. Is % sign in lua code causing the error?

13

You have defined \findgcd with two arguments, but you only supply one:

\findgcd{5}{10}

will work.

If you want the syntax \findgcd{5,10}, then declare it:

\documentclass{article}
\usepackage{luacode}

\begin{luacode}
function gcd(a,b)
    if b ~= 0 then
        return gcd(b, a % b)
    else
        return math.abs(a)
    end
end
\end{luacode}

\newcommand\findgcd[1]{\directlua{tex.sprint(gcd(#1))}}

\begin{document}
\findgcd{5,10}
\end{document}

Here's a simple package code, save as gcd.sty:

\ProvidesPackage{gcd}[2019/07/22]
\RequirePackage{luacode}

\begin{luacode}
function gcd(a,b)
    if b ~= 0 then
        return gcd(b, a % b)
    else
        return math.abs(a)
    end
end
\end{luacode}

\newcommand\findgcd[2]{\directlua{tex.sprint(gcd(#1,#2))}}

\endinput

Now your document, as soon as gcd.sty is in a directory read by the TeX engines, can be

\documentclass{article}
\usepackage{gcd}

\begin{document}
\findgcd{5}{10}
\end{document}
  • Is it possible to store this function as a package? I mean something like this. \usepackage{gcd} and with this package \findgcd command will be available to use it anywhere in document. – user61681 Jul 22 at 11:40
  • @user61681 Yes, write a package and upload it to CTAN. – egreg Jul 22 at 11:56
  • Could you share some resources? How to write package for this type of lua functions? – user61681 Jul 22 at 12:03
  • 1
    Thanks for your detailed help. You are great...! Just one last query, though it is out of scope here. I am trying to learn how to write latex macros (own commands, environments etc.). I couldn't find any resources for that. I have programming background but still find it difficult to learn latex programming. Could you share some resources if you know? Thanks again. – user61681 Jul 22 at 12:28
  • @user61681 It's best if they're documented. – egreg Jul 22 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.