Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the number of values in a given range divisible by a given value?

Tags:

I have three numbers x, y , z.

For a range between numbers x and y.

How can i find the total numbers whose % with z is 0 i.e. how many numbers between x and y are divisible by z ?

like image 713
Dexter Avatar asked May 05 '13 05:05

Dexter


People also ask

How do you find what numbers a number is divisible by?

A number is divisible by another number if it can be divided equally by that number; that is, if it yields a whole number when divided by that number. For example, 6 is divisible by 3 (we say "3 divides 6") because 6/3 = 2, and 2 is a whole number.

How many numbers from 1 to N are divisible by all numbers from 2 to 10?

So, the count of such numbers is N / 2520.

How do you find out if the number that the user entered is divisible by the other in python?

In Python, the remainder operator (“%”) is used to check the divisibility of a number with 5. If the number%5 == 0, then it will be divisible.

How do you find the number of multiples in a given range?

Thus including 20 and 300 it has 60−4+1=57 multiples. If suppose instead of 300, you had x on the end where x is not a multiple of 5 then you just take first multiple of 5 when you start walking left on integer line from x, i.e. if x=304, you replace it by 300 again.


Video Answer


1 Answers

It can be done in O(1): find the first one, find the last one, find the count of all other.

I'm assuming the range is inclusive. If your ranges are exclusive, adjust the bounds by one:

  • find the first value after x that is divisible by z. You can discard x:

    x_mod = x % z;  if(x_mod != 0)   x += (z - x_mod); 
  • find the last value before y that is divisible by y. You can discard y:

    y -= y % z; 
  • find the size of this range:

    if(x > y)   return 0; else   return (y - x) / z + 1; 

If mathematical floor and ceil functions are available, the first two parts can be written more readably. Also the last part can be compressed using math functions:

 x = ceil  (x, z);  y = floor (y, z);  return max((y - x) / z + 1, 0); 

if the input is guaranteed to be a valid range (x >= y), the last test or max is unneccessary:

 x = ceil  (x, z);  y = floor (y, z);  return (y - x) / z + 1; 
like image 188
John Dvorak Avatar answered Sep 20 '22 15:09

John Dvorak