int a,b,c,d=0;
cin>>a>>b>>c;
for (int i=a;i<=b;i++)
{
if (i%c==0){d++;}
}
cout<<d;
So this is the code, a..b
is the number range, c
is the divisor, and d
counts the multiples of c
. For example when a=5, b=15, c=3
, d
equals 4
, because "6, 9, 12, 15" are the multiples between 5 and 15.
I need to find faster way to do this, can anyone help?
Let B = b * M and A = a * M The count of numbers divisible by 'M' between A and B will be equal to b - a. Example: A = 25, B = 70, M = 10. Now, a = 2, b = 7. Count = 7 - 2 = 5.
So, the count of such numbers is N / 2520.
Therefore, a number is divisible by 2 if it has a 0, 2, 4, 6, or 8 in the ones place. For example, 54 and 2,870 are divisible by 2, but 2,221 is not divisible by 2. A number is divisible by 4 if its last two digits are divisible by 4. For example, 780, 52, and 80,744 are divisible by 4, but 7,850 is not divisible by 4.
Divisibility by 7 can be checked by a recursive method. A number of the form 10a + b is divisible by 7 if and only if a – 2b is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a small number.
One way is to do it like this (no loops required):
int lower = (a + c - 1) / c; // find lowest divisor (round up)
int upper = b / c; // find higher divisor (round down)
d = upper - lower + 1; // get no of divisors
For your example case, lower
will be 2, upper
will be 5, giving d
equal to 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With