Reputation: 35
This is simple mathematics I guess, but I just can't figure it out + I'm new to coding. I need to find out how many numbers are divisible by x in a range. Here's an example: I need to find how many numbers in the range 11 to 30 are divisible by 3. The answer is 7, and I already coded it:
while (a <= b) {
if (a % 3 == 0) {
c++;
a++;
else {
a++;
}
}
HOWEVER, this works horribly for large numbers as I check every single number. I tried doing c = (b-a)/3
, but obviously this doesn't work for all examples, just like it doesn't for the one above. So, could you please help me find some sort of a simple equation that would calculate this for me. I'm feeling so stupid for not being able to figure this one out.
Upvotes: 1
Views: 993
Reputation: 122493
In psudo-code:
a
: c = math.ceil(a / 3) * 3
.b
: d = math.floor(b / 3) * 3
.(d - c) / 3 + 1
.In the example of 11
to 30
, c
is 12
, and d
is 30
, the final answer is 7
.
Upvotes: 2
Reputation: 706
You're close! Do something like (no idea what you're coding in so this will be pseudo-code):
function numDiv(int a, int b, int divBy) {
int x;
if(a>b) x=1+a-b;
else x=1+b-a;
return floor(x/divBy);
}
the floor and +1 will should get you there.
Upvotes: 0