'Divide number into many unequal parts JavaScript

I want to split a number between 20 and 50 into unequal parts.

For example:

30 = 1x20 & 1x10

45 = 2x20 1x5

or 38 = 1x20 1x10 1x5 1x2 1x1

document.getElementById("jscolor").style.color = "red";
var tokenResult = prompt(`Please enter a number between 10 and 50: `);
var divideBy = 5;
tokenResult = parseInt(tokenResult);
document.write(tokenResult + ` = `);
for (var i = 0; i < divideBy; i++) {
    document.write(`${tokenResult / divideBy} `);
}

Which outputs something like:

25 = 5 5 5 5 5

I haven't managed to split it into unequal parts that aren't random.



Solution 1:[1]

Baically ou need an array of denominations, like

[20, 10, 5, 2, 1]

Then you need to take your value and divide it through the largest value. Take the count, an integer value and store it along with the denomination.

Substract the product of count and denomination value from the input value.

If your new value is not zero take the second large value from the denominations array and perfor the last steps again.

Finally get all counts and denominations into a readable string and make an output.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nina Scholz