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 !!!
CodePudding user response:
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.
CodePudding user response:
If you want to see how many times X can be divided by Y, you do
yz =x
z*log(y) = log(x)
z = log(x)/log(y)
and from here you either floor(z) or ceil(z) depending on your problem.
CodePudding user response:
This is probably not what you're looking for, but it's a shorthand way of getting to where you're going.
const fun = (x, y) => {
let r = x % y; // store our modulus here
return !r ? [x, 0] : [(y - r x), y - r];
// if there is no remainder, return the dividend and zero: x, 0
// otherwise, the next whole number result is found by
// subtracting the modulus from the divisor and adding the dividend: (y - r x)
// and the difference between the new divisor and the old divisor is the divisor minus the modulus: (y - r)
}
I have it returning in an array but you can easily convert that into your string format with join(',')
const fun = (x, y) => {
let r = x % y;
return !r ? [x, 0] : [(y - r x), y - r];
}
console.log(fun(23, 5))
console.log(fun(33, 2))