AtCoder Beginner Contest 048 B - Between a and b

Problem Statement

You are given nonnegative integers a

and b (ab), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x

?

Constraints

  • 0ab1018
  • 1x1018
 

Input

The input is given from Standard Input in the following format:

a b x
 Output

Print the number of the integers between a

and b, inclusive, that are divisible by x.

 

 

易知0到a内整除x的数的个数为a/x+1,所以a不整除x时答案为(b/x-a/x),在整除时还要再加一。

注意,不要把(b/x-a/x)合并为(b-a)/x,虽然在数学上是对的,但在计算机中除法是下取整的,可能会导致精度不对。例如a=2,b=6,x=3时b/x-a/x=2,但(b-a)/x=1。

下为代码:

 

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int main()
 5 {
 6     unsigned long long a, b, x, ans;
 7     cin >> a >> b >> x;
 8     if (a > b)
 9     {
10         cout << 0;
11         return 0;
12     }
13     //ans = (b - a) / x;
14     ans = b / x - a / x;
15     if (a%x == 0)
16         ans++;
17     cout << ans;
18     return 0;
19 }

 

posted @ 2021-04-03 13:47  许崇智  阅读(136)  评论(0)    收藏  举报