Here we will randomly chose $A$, $B$ and $C$ such that $Ax^2+Bx+C$ can be factored easily as $(ax+b)(cx+d)$, where $a$, $b$, $c$ and $d$ are integers. We also make sure that $a$ and $b$ have no common factor, also $c$ and $d$ have no common factor. We also make sure that $a$ and $c$ are positive. $b$ and $d$ can be positive or negative chosen by the randomsign() routine.
Here is the modified code of changeProblem() and the new function called cfactor() to find common factor and the sign chooser function randomsign().
Note also that if the leading coefficient is 1, it is not displayed. This is because the routine printNum has been modified to take an additional parameter named leading which tells if the number is a leading coefficient.
function randomsign() {
if (Math.floor(2 * Math.random())) return 1;else return -1;
}
function cfactor(m,n) {
p = Math.abs(m);q = Math.abs(n);
min = Math.min(p,q);
f = 1;
for (i=2;i<=min;i++)
while (p % i == 0 && q % i == 0) {
p/=i;q/=i;;f*=i;
}
return f;
}
function printNum(n, showone,leading) {
str = ((n > 0 ) ? (!leading ? "+" : "") : "-");
str += showone ? Math.abs(n) : ((Math.abs(n) == 1) ? "" : Math.abs(n));
return str;
}
function changeProblem() {
a = Math.floor(10 * Math.random()) + 1;
b = randomsign() * (Math.floor(10 * Math.random()) + 1);
c = Math.floor(10 * Math.random()) + 1;
d = randomsign() * (Math.floor(10 * Math.random()) + 1);
f1 = cfactor(a,b);f2 = cfactor(c,d);a /=f1 ;b/=f1;c/=f2;d/=f2;
A = a*c;B = a*d+b*c;C = b*d;
divElement = document.getElementById("equation");
str = "$" + printNum(A,false,true) + "x^2" + printNum(B,false,false) + "x" + printNum(C,true,false) + "$";
str += "$=" + printNum(A,false,true) + "x^2" + printNum(a*d,false,false) + "x" + printNum(b*c,false,false) + "x" + printNum(C,true,false) + "$";
str += "$=" + printNum(a,false,true) + "x(" + printNum(c,false,true) + "x" + printNum(d,true,false) + ")" + printNum(b,false,false) + "(" + printNum(c,false,true) + "x" + printNum(d,true,false) + ")$";
str += "$=(" + printNum(c,false,true) + "x" + printNum(d,true,false) + ")("+ printNum(a,false,true) + "x" + printNum(b,true,false) + ")$";
divElement.innerHTML = str;
MathJax.Hub.Queue(["Typeset",MathJax.Hub,"equation"]);
}