More proof of concept than anything else. It could be written in pure TeX, but I was lazy. Requires LuaLaTeX.
\RequirePackage{luatex85}
\documentclass[varwidth,border=5]{standalone}
\usepackage{amsmath,luacode}
\textwidth=8cm
\begin{luacode*}
function gcd(u, v)
u = math.abs(u)
v = math.abs(v)
if u == v then
return u
end
if u == 0 then
return v
end
if v == 0 then
return u
end
if u % 2 == 0 then
if v % 2 == 1 then
return gcd(math.floor(u / 2), v)
else
return gcd(math.floor(u / 2), math.floor(v / 2)) * 2
end
else
if v % 2 == 0 then
return gcd(u, math.floor(v / 2))
end
if u > v then
return gcd(math.floor((u - v) / 2), v)
else
return gcd(math.floor((v - u) / 2), u)
end
end
end
function solveQuadratic(a, b, c)
local d, x1, x2;
d = b * b - 4 * a * c
if d >= 0 then
x1 = (-b - math.sqrt(d)) / (2 * a)
x2 = (-b + math.sqrt(d)) / (2 * a)
if x1 ~= math.floor(x1) or x2~= math.floor(x2) then
x1 = nil
x2 = nil
end
else
x1 = nil
x2 = nil
end
return {x1 = x1, x2 = x2}
end
function coef(a)
if a == 1 then
return ''
else
return a
end
end
function formatCoef(a, c)
local str = ''
if a ~= 0 then
if math.abs(a) > 1 or c == '' then
str = str .. math.abs(a)
end
if a < 0 then
str = '-' .. str
end
str = str .. c
end
return str
end
function formatQuadratic(a, b, c)
local str = ''
str = formatCoef(a, 'x^2')
if str ~= '' and b > 0 then
str = str .. '+'
end
str = str .. formatCoef(b, 'x')
if str ~= '' and c > 0 then
str = str .. '+'
end
str = str .. formatCoef(c, '')
return str
end
function formatFactoredQuadratic(x1, x2, g)
local str = ''
if x1 == 0 then
str = 'x'
else
if x1 > 0 then
str = str .. '(x + ' .. x1 .. ')'
else
str = str .. '(x ' .. x1 .. ')'
end
end
if x2 == 0 then
str = str .. 'x'
else
if x2 > 0 then
str = str .. '(x + ' .. x2 .. ')'
else
str = str .. '(x ' .. x2 .. ')'
end
end
if g ~= nil then
if math.abs(g) > 1 then
str = g .. str
elseif g == -1 then
str = '-' .. str
end
end
return str
end
function genEq(n, gc)
local a, b, c, g, h1, h2, eqs
if gc == nil then
h1 = 1
h2 = 1000 -- some large number
else
h1 = 0
h2 = 1
end
eqs = {n=0}
for a = -n,n do
for b = -n,n do
for c = -n,n do
if a ~= 0 and b ~=0 and c ~= 0 then
g = gcd(gcd(a, b), c)
if g > h1 and g <= h2 then
if a < 0 then
s = solveQuadratic(-a, -b, -c)
g = -g
else
s = solveQuadratic(a, b, c)
end
if s.x1 ~= nil and s.x2 ~= nil then
table.insert(eqs, {eq = formatQuadratic(a, b, c),
fct = formatFactoredQuadratic(-s.x1, -s.x2, g)})
eqs.n = eqs.n + 1
end
end
end
end
end
end
return eqs
end
\end{luacode*}
\begin{document}
\begin{align*}
\intertext{Lacking a non-1 GCD}
\directlua{%
eqs = genEq(10,1)
for i = 1,5 do
x = math.random(1, eqs.n)
tex.print(eqs[x].eq .. ' &= ' .. eqs[x].fct ..'\noexpand\\\noexpand\\')
end
}
\\\intertext{Not lacking a non-1 GCD}
\directlua{%
eqs = genEq(10)
for i = 1,5 do
x = math.random(1, eqs.n)
tex.print(eqs[x].eq .. ' &= ' .. eqs[x].fct ..'\noexpand\\\noexpand\\')
end
}
\\
\end{align*}
\end{document}
