Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster algorithm to count how many numbers are divisible by a specific integer in a range

Tags:

c++

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?

like image 281
Konrad Avatar asked Nov 06 '14 10:11

Konrad


People also ask

How do you find the number of values in a given range divisible by a given value?

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.

How many numbers from 1 to N are divisible by all numbers from 2 to 10?

So, the count of such numbers is N / 2520.

How do you know if a number is divisible by a set of numbers?

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.

What an algorithm to check a number is divisible by 7 or not?

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.


Video Answer


1 Answers

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.

like image 156
Paul R Avatar answered Oct 03 '22 02:10

Paul R