The non script part of my calculator is this (With all the inputs):
<body>
<p class="box">Fraction Calculator</p>
<input type="number" id="n1">
<select id="operation">
<option value="1">X</option>
<option value="2">/</option>
<option value="3">+</option>
<option value="4">-</option>
</select>
<input type="number" id="n2">
<br>
<input type="number" id="n3">
<input type="number" id="n4" style="margin-left:37px">
<br>
<button style="margin-left:130px"; onClick="document.getElementById('fraction').innerHTML = option()">Go!</button>
<p id="fraction"></p>
</body>
And my option function is this:
function option()
{
selection = document.getElementById('operation').value;
if(selection == "1"){
a = multiply();
return a
}
else if(selection == "2"){
b = division();
return b
}
else if(selection == "3"){
c = addition();
return c
}
else{
d = subtraction();
return d
}
}
So my current code for my multiplication part fo my calculator is this:
function multiply()
{
Number1 = parseInt(document.getElementById("n1").value);
Number2 = parseInt(document.getElementById("n2").value);
Number3 = parseInt(document.getElementById("n3").value);
Number4 = parseInt(document.getElementById("n4").value);
var topm = Number1 * Number2;
var botm = Number3 * Number4;
return topm + "/" + botm; }
So currently my calculator works but none of the fractions are simplified. How would I be able to simplify these fractions? (I am decently new to code) Thanks :) Here is the JSFiddle link: https://jsfiddle.net/Ethang70/npgL3gd9/
To simplify fractions, what you do is that you calculate the greatest common divisor between the denominator and numerator, and divide both with the GCD.
One way to calculate the GCD is to use the Eucledian algorithm.
One implementation in Javascript could be:
function gcd(a,b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}
}
And thereafter, when you print your fraction you can do something like this:
function multiply()
{
Number1 = parseInt(document.getElementById("n1").value);
Number2 = parseInt(document.getElementById("n2").value);
Number3 = parseInt(document.getElementById("n3").value);
Number4 = parseInt(document.getElementById("n4").value);
var topm = Number1 * Number2;
var botm = Number3 * Number4;
var divisor = gcd(topm, botm);
topm = topm / divisor;
botm = botm / divisor;
return topm + "/" + botm;
}
Good luck!