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=⌊yd⌋−⌊xd⌋
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
x≠1
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):
⌊9992⌋−⌊1002⌋=499−50=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
x−1
x1?
(1')
n=⌊yd⌋−⌊x−1d⌋
nydx1d
(1') returns the correct answer for this specific input now, but I am not sure if it will break my other solutions.