Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Find out how many times a number goes into another number evenly

Tags:

javascript

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>
like image 301
user1822824 Avatar asked Jan 24 '13 05:01

user1822824


People also ask

How many times a number contains another?

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).

How do you figure out how many times a number is divisible by 2?

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).

How do you check if a number is divisible by another number JS?

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 .


1 Answers

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);
like image 155
alex Avatar answered Sep 22 '22 20:09

alex