【DidaOJ】[1133]Thanksgiving KK Special - The First Snow of 2015

Problem Description

Loading...

Problem Analysis

Core algorithm:

For positive integers n and k, the count of numbers from 1 to n that are divisible by k is:

$$ \lfloor \dfrac{n}{k} \rfloor $$

In other words, you just divide n by k and take the integer part.

So for the interval [a, b], the count of numbers divisible by k can be computed with this formula:

$$ \lfloor \dfrac{b}{k} \rfloor - \lfloor \dfrac{a-1}{k} \rfloor $$

But in the actual implementation, because of C++’s default integer division semantics, negative results don’t behave as expected, so you need to handle the negative-result case yourself.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <cstdio>  

typedef long long ll;  
  
bool is_same_sign(ll a, ll b)  
{  
    return (a ^ b) >= 0;  
}  
  
ll get_floor_div(ll a, ll b)  
{  
    if (b == 0)  
    {  
        return 0; // Handle division by zero  
    }  
    ll res = a / b;  
    if (!is_same_sign(a, b) && a % b != 0)  
    {  
        res--;  
    }  
    return res;  
}  
  
ll get_div_number(ll k, ll x, ll y)  
{  
    if (k == 0)  
    {  
        return 0;  
    }  
    if (k < 0)  
    {  
        k = -k;  
    }  
    return get_floor_div(y, k) - get_floor_div(x - 1, k);  
}  
  
int main()  
{  
    int T;  
    scanf("%d", &T);  
    while (T--)  
    {  
        int k, x, y;  
        scanf("%d %d %d", &k, &x, &y);  
        printf("%lld\n", get_div_number(k, x, y));  
    }  
    return 0;  
}  

Problem link: Thanksgiving KK Special — The First Snow of 2015 - Problem Details - Problems - DidaOJ

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...