Is there a simple way to find how many times a number goes into another number evenly in JavaScript?
Say 11 divided by 4 --- I know 4 goes into 11 2 times evenly
I have this code but I thought there was a simpler way that I maybe forgetting?
<script>
a = 11;
b = 4;
i = a % b;
i2 = a - i;
solution = i2 / b;
document.write(solution); // 2
</script>
In mathematics, a ratio shows how many times one number contains another. For example, if there are eight oranges and six lemons in a bowl of fruit, then the ratio of oranges to lemons is eight to six (that is, 8:6, which is equivalent to the ratio 4:3).
Is there a smart manner to determine how many times a given integer n number can be divided by two? For example, 2 can be divided one time by 2. Any odd number can't be divided by 2. A number that is a power of 2 can be divided by two exactly log n ( 8 can be divided lg 8 = 3 times by two because 8 = 2^3).
We will use the modulo operator, % , to check if one number is evenly divisible by another number. The modulo operator gives the remainder obtained by dividing two numbers. If a number is evenly divisible, the operation will return 0 .
What about...
Math.floor(11 / 4);
If you're wanting to handle negative numbers (thanks Ted Hopp), you could use ~~
, |0
or any other bitwise trick that will treat its operand as a 32 bit signed integer. Keep in mind, besides this being confusing, it won't handle a number over 32bits.
~~(11 / 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With