how many positive integers are divisible by a number d in range [x,y]?

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;
share improve this answer
 

You could make a function f to calculate the number of multiples for any number n, then

  • calculate a = f(y)
  • calculate b = f(x-1) since x is included (x > 0)
  • the result is a - b

The algorithm (function f) to calculate the number of multiples of base b for a number n is simple

multiples = n / b      ( '/' is integer division)

That should give you enough material to build the actual functions.
The functions are of course O(1)

The whole algorithm comes as (x > 0)

function f(n, b) {
    return n / b
}

print f(y) - f(x-1)

Examples of results you should find

  • [1, 1000] ÷ 6 => 166
  • [100, 1000000] ÷ 7 => 142843
  • [777, 777777777] ÷ 7 => 111111001
share improve this answer
 
1 
I don't understand "function f to calculate the number of multiples for any number n". Do you mean integer division? –  Jan Dvorak  May 5 '13 at 6:29
 
Yes, (integer division) is written below the multiples line –  ringø  May 5 '13 at 6:30
 
very clever!!!! –  Bin Chen  May 5 '13 at 6:32

I also encountered this on Codility. It took me much longer than I'd like to admit to come up with a good solution, so I figured I would share what I think is an elegant solution!

Straightforward Approach 1/2:

O(N) time solution with a loop and counter, unrealistic when N = 2 billion.

Awesome Approach 3:

We want the number of digits in some range that are divisible by K.

Simple case: assume range [0 .. n*K], N = n*K

N/K represents the number of digits in [0,N) that are divisible by K, given N%K = 0 (aka. N is divisible by K)

ex. N = 9, K = 3, Num digits = |{0 3 6}| = 3 = 9/3

Similarly,

N/K + 1 represents the number of digits in [0,N] divisible by K

ex. N = 9, K = 3, Num digits = |{0 3 6 9}| = 4 = 9/3 + 1

I think really understanding the above fact is the trickiest part of this question, I cannot explain exactly why it works. The rest boils down to prefix sums and handling special cases.


Now we don't always have a range that begins with 0, and we cannot assume the two bounds will be divisible by K. But wait! We can fix this by calculating our own nice upper and lower bounds and using some subtraction magic :)

  1. First find the closest upper and lower in the range [A,B] that are divisible by K.

    • Upper bound (easier): ex. B = 10, K = 3, new_B = 9... the pattern is B - B%K
    • Lower bound: ex. A = 10, K = 3, new_A = 12... try a few more and you will see the pattern is A - A%K + K
  2. Then calculate the following using the above technique:

    • Determine the total number of digits X between [0,B] that are divisible by K
    • Determine the total number of digits Y between [0,A) that are divisible by K
  3. Calculate the number of digits between [A,B] that are divisible by K in constant time by the expression X - Y

Website: https://codility.com/demo/take-sample-test/count_div/

class CountDiv {
    public int solution(int A, int B, int K) {
        int firstDivisble = A%K == 0 ? A : A + (K - A%K);
        int lastDivisible = B%K == 0 ? B : B - B%K; //B/K behaves this way by default.
        return (lastDivisible - firstDivisible)/K + 1;
    }
}

This is my first time explaining an approach like this. Feedback is very much appreciated :)

share improve this answer
 

This is one of the Codility Lesson 3 questions. For this question, the input is guaranteed to be in a valid range. I answered it using Javascript:

function solution(x, y, z) {
    var totalDivisibles =  Math.floor(y / z),
        excludeDivisibles = Math.floor((x - 1) / z),
        divisiblesInArray = totalDivisibles - excludeDivisibles;
   return divisiblesInArray;
}

https://codility.com/demo/results/demoQX3MJC-8AP/

(I actually wanted to ask about some of the other comments on this page but I don't have enough rep points yet).

share improve this answer
 

Divide y-x by z, rounding down. Add one if y%z < x%z or if x%z == 0.

No mathematical proof, unless someone cares to provide one, but test cases, in Perl:

#!perl
use strict;
use warnings;
use Test::More;

sub multiples_in_range {
  my ($x, $y, $z) = @_;
  return 0 if $x > $y;
  my $ret = int( ($y - $x) / $z);
  $ret++ if $y%$z < $x%$z or $x%$z == 0;
  return $ret;
}   

for my $z (2 .. 10) {
  for my $x (0 .. 2*$z) {
    for my $y (0 .. 4*$z) {
      is multiples_in_range($x, $y, $z),
         scalar(grep { $_ % $z == 0 } $x..$y),
         "[$x..$y] mod $z";
    }
  }
}

done_testing;

Output:

$ prove divrange.pl 
divrange.pl .. ok      
All tests successful.
Files=1, Tests=3405,  0 wallclock secs ( 0.20 usr  0.02 sys +  0.26 cusr  0.01 csys =  0.49 CPU)
Result: PASS
share improve this answer
 
1 
Seems correct (and would be the best answer), but you'll need to convince me you're not off-by-one ;-) –  Jan Dvorak  May 5 '13 at 6:33
 
yes.Not off-by-one is the most difficult part of this question... –  Bin Chen  May 5 '13 at 6:36
 
@JanDvorak I don't think I'm up to proving it at 2:30 AM, but it seems to work quite well (after my edit). –  hobbs  May 5 '13 at 6:37
 
@hobbs throw in your test cases, then :-) (and a disclaimer) –  Jan Dvorak  May 5 '13 at 6:37 
1 
Ungh. Dollars everywhere :-) –  Jan Dvorak  May 5 '13 at 6:47

Here is my short and simple solution in C++ which got 100/100 on codility. :) Runs in O(1) time. I hope its not difficult to understand.

int solution(int A, int B, int K) {
    // write your code in C++11
    int cnt=0;
    if( A%K==0 or B%K==0)
        cnt++;
    if(A>=K)
        cnt+= (B - A)/K;
    else
        cnt+=B/K;

    return cnt;
}

What is wrong with my algorithm for finding how many positive integers are divisible by a number d in range [x,y]?

I have been solving basic counting problems from Kenneth Rosen's Discrete Mathematics textbook (6th edition). These come from section 5-1 (the basics of counting), pages 344 - 347. 

This question is not specifically about finding an answer to a problem or being given the correct equation, but whether my reasoning is sound. Therefore I would find it hard to argue this is a duplicate of seemingly similar questions like this one or this one

The problems I have been dealing with come of the form How many positive integers in range [x,y] are divisible by d? All additional questions are based on the composition of the information learned in these, e.g. how many positive integers in range [x,y] are divisible by d or e?

To answer the simple question I wrote this "equation/algorithm," which takes as input an inclusive range of positive integers  [x,y] xy and a positive integer  d d, and returns  n n, the total number of positive integers in range  [x,y] xy which are divisible by  d d

(1)  n=ydxd nydxd

The idea is that in order to count how many positive integers are divisible by  d d from  [1,m] 1m, we simply calculate  md md, because every  dth dth positive integer must be divisible by  d d. However, this does not work when given a range  [x,y] xy where  x1 x1 or when  x>1 x1. So we need to subtract the extra integers we counted, which is  xd xd, i.e. the number of positive integers divisible by  d d from  [1,x] 1x

For a sanity check, I also wrote a brute force algorithm that does a linear search over every positive integer in the range  [x,y] xy and counts it if  x mod d==0 x mod d0. It also can list out the integers it picked, in case I am feeling really paranoid. 

With (1) I've been getting the correct answers except on this problem/input: How many positive integers between 100 and 999 inclusive are odd? My solution was to calculate how many are even, and subtract this from the total number of positive integers in range  [100,999] 100999. To find the evens I simply use the algorithm in (1):

99921002=49950=449 9992100249950449

But this answer is wrong, since there actually  450 450 even numbers in range  [100,999] 100999 by the brute force algorithm. (1) is somehow counting off by 1. My question is, why is (1) failing for this input of  (2,[100,999]) 2100999 but so far it's worked on every other input? What do I need to do to fix (1) so it produces the correct answer for this case? Perhaps I'm actually over counting because  x x should actually be  x1 x1?

(1')  n=ydx1d nydx1d

(1') returns the correct answer for this specific input now, but I am not sure if it will break my other solutions. 

share cite improve this question
 

3 Answers

up vote 1 down vote accepted

After computing the number of positive multiples of  d d less than or equal to  y, y you correctly want to subtract the multiples that are not actually in the range  [x,y]. xy Those are the multiples that are less than  x. x When  x x is divisible by  d, d then  xd xd counts all multiples of  d d up to and including  x x itself. So as you surmised, you want to subtract  x1d x1d instead. This is true for any divisor, not just  d=2. d2.

share cite improve this answer
 
 
You have identified and explained the problem nicely. –  Ross Millikan  Sep 14 '14 at 2:38

another counterexample is [13,6] and 2. the formula seems to be off by 1 if d exactly divides x or (x and y) because then the # of integers in the range [a, b] = b - a + 1. 

share cite improve this answer
 

Suppose you have

(k1)d<xkd<(k+1)d<<(k+n)dy<(k+n+1)d. k1dxkdk1dkndykn1d
Then, you always have  yd=k+n ydkn is  k+n kn. On the other hand, if  x x is divisible by  d d, then  xd=k xdk, whereas if  x x isn't divisible by  d d, then  xd=k1 xdk1. To rectify this, instead use  xd xd which always returns  k k. Your solution is then
n+1=(n+k)k+1=ydxd+1. n1nkk1ydxd1


p.s.

(k1)d<xkd(k1)dx1<kdx1d=k1 k1dxkdk1dx1kdx1dk1
so that
n+1=(n+k)(k1)=ydx1d. n1nkk1ydx1d
The formulas in blue and red produce the same answer.

share cite improve this answer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值