MATH PROBLEM

hey can anyone tell me the count of numbers ending with 2,3,9 within a given range?
is there any trick for that.

here's sample

find numbers between 11 and 33
answer is 8
You just have to determine whether a number ends with 3, 6 or 9. Here is an example:

1
2
3
4
5
6
// MIN and MAX are two constant int variables signifying the range of numbers
// between which to search for the number of occurrences of 3, 6, and 9 respectively.
for (int i{ MIN }; i <= MAX; ++i)
{
    i % 10 == 2 || i % 10 == 3 || i % 10 == 9 ? ++count : count += 0;
}
Please don't try to find solutions online while doing the codechef contest.
It'll be of a loss to you only man.
There are 3 numbers ending in 2, 3, or 9 between 10n and 10(n+1). So you can just count those up and adjust. No need for a loop.

1
2
3
4
5
6
7
8
9
10
    int cnt = (hi / 10 - lo / 10) * 3;

    int m = lo % 10;
    if      (m > 3) cnt -= 2;
    else if (m > 2) cnt--;

    m = hi % 10;
    if      (m == 9) cnt += 3;
    else if (m >  2) cnt += 2;
    else if (m == 2) cnt++;


If you want to avoid conditional tests, you could use a table of adjustments:
1
2
3
                 // 0  1  2  3  4  5  6  7  8  9 10
    int adjust[] = {0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 3};
    int cnt = (hi / 10 - lo / 10) * 3 - adjust[lo%10] + adjust[hi%10+1];


Last edited on
Topic archived. No new replies allowed.