For an assignment, I need to write code that takes 3 inputs: a lower bound, an upper bound, and a divisor. The program is then supposed to output the number of integers between the lower and upper bounds that are evenly divisible by the divisor.
It sounds easy enough, but here's the catch: I'm forbidden from using loops of any kind (only sequential commands), no functions outside of main(), and the only libraries I can use are iostream, iomanip, and fstream, which (as far as I know) are irrelevant to the mathematical aspect of this problem.
The hint we were given was that we need to find the number of integers evenly divisible by the divisor below the upper bound, and then the number of integers evenly divisible by the divisor below the lower bound, and then subtract the second result from the first.
That part is easy enough to understand, and this would be simple if loops were allowed. But does anyone know how I can solve this using solely sequential commands?
Any help would be greatly appreciated.
Edit: In case it helps at all, here're some example values:
Lower bound: 10
Upper bound: 20
Divisor: 2
Output 6
anup30: That was actually very helpful, however I'm not allowed to use 'if' statements, either...
Edit: shadowCODE, we're not supposed to use them because the class I'm taking hasn't gotten to them yet. We lose marks for using code that hasn't been discussed in class.
Edit #2: I think I've figured it out, using anup30's advice. This formula seems to work:
This one works with the range/divisor you provided (when all values are of the integer datatype). I don't think there are any problems with it. Can anyone prove that it doesn't work?
The suggestion you provided doesn't work (for the range [10,20], d = 2, it outputs 5 instead of 6).
giblit: I'm sorry to say that I'm not allowed to use propositions, either. I apologize for not mentioning that earlier.
It's fine. Also your second solution appears to work with these 4 cases:
1) upper - lower < divisor && upper % divisor != 0 && lower % divisor != 0 //you have this taken care of
2) upper % divisor == 0 && lower % divisor != 0 //you have this taken care of
3) upper % divisor != 0 && lower % divisor == 0 //you have this taken care of
4) upper % divisor == 0 && lower % divisor == 0 //you have this taken care of
You can test it with something like:
[4, 14] d = 4 (4, 8, 12 -> 3 is result)
[5, 16] d = 4(8, 12, 16 ->3 is result)
[4, 12] d = 4(4, 8, 12 ->3 is result)
[5, 7] d = 4 ( ->0 is result)
With your formula I get:
result = (14/4) - ((4-1)/4) = 3 - (3/4) = 3 - 0 = 3 <--correct
result = (16/4) - ((5-1)/4) = 4 - (4/4) = 4 - 1 = 3 <--correct
result = (12/4) - ((4-1)/4) = 3 - (3/4) = 3 - 0 = 0 <--correct
result = (7/4) - ((5-1)/4) = 1 - (4/4) = 1 - 1 = 0 <--correct