The goal of the function is to convert from a fraction to a mixed number. So far I can get the integer part but I have problems simplifying the dividend and the divisor of the number (for example from 6/9
to 2/3
). Thank you
function convertirFraccion(s) {
s = s.split('/').map(a => Number(a))
let modulo = s[0] % s[1]
let resto = modulo / s[1]
let numeral = Math.floor(s[0] / s[1])
return modulo == 0 ? numeral : `${numeral} ${modulo}/${s[1]}`
}
console.log(convertirFraccion('24/9'));
The code you have works very well, you only have a problem when doing the simplification of the dividend and the divisor.
In the simplification you reduce both numbers by dividing them by their prime factors until they are both primes of each other (have no prime factors in common).
For this, in your code you verify the result of
modulo
, if it is 0 it implies that the division is exact and only an integer result is shown.If not, you will have to decompose the numbers, for that you start by checking the module of both numbers starting with 2 up to half of the dividend, (it could be more optimal with the square root since the largest number that can divide exactly a number is less than or equal to its square root).
Every time both modules result in 0, you divide the number by the current factor. This factor is then increased.
At the end to show the mixed number you can check if the integer part is greater than 0, otherwise there is no need to show it.
The code is as follows:
This is just a rough way to solve it, I think it can be optimized a little more, greetings.
The problem was not thought of in the event that they inserted one of the negative numbers or both... which complicates things a bit, I leave this function here... by brute force but which checks all the cases