Search code examples
javascriptreactjsdivisionmodulo

How do I return the amount of times number A can be divided by number B untill it includes a remainder?


for context here is my problem:

I have a table of parts. A part is produced from a set of materials, let's call the constant materials variable z. So this table is a table of parts all produced from a set of materials. Each row in this table is a new part. There is also a column indicating the amount of parts that will be produced from 1 set of materials.

So if I have:

var z = 1 //just some constant

var x = 5 //the amount of parts produced from a single set of materials

var y = 23 //the total amount of parts that have to be made 

I know the amount of parts produced from a set of materials, and I know the amount of parts that need to be produced. I can never produce less parts than are needed, so I know that 4 sets of materials will produce me 20 parts and I would still be 3 short. If i use 5 sets of materials I can produce 25 parts with a remainder of 2 parts.

My issue is that I tried to solve this using mod, but I'm making a mistake somewhere

//Fun
    const fun = async () => {
        try {

            
            let x = 23;
            let y = 5;
            const result = x/y

            if(x%y == 0) {
                console.log(x, ' divided by', y, ' has remainder of: ', x%y);
                console.log(y, ' divided by', x, ' has remainder of: ', y%x);

            }
            else {
                console.log(x, ' divided by', y, ' has remainder of: ', x%y); 
                console.log(y, ' divided by', x, ' has remainder of: ', y%x);
            }
 
        } catch (err) {
            console.log(err.message);
        }
    }

So to further add clarity I would always want to find the maximum amount of times a number can be divided by something, and if it has a remainder then record the remainder. Would a possible solution be to distinguish between positive or negative remainders? Any help is appreciated, thank you !!!


Solution

  • Math.floor( A/B ), where A is the desired number and B is the number of pieces in a set, will give you the number of divisions before remainder (since a division is just the number of times B can be subtracted from A, then we use Math.floor to round down), (A%B) will give you the remainder thereafter.