2018湘潭邀请赛K题题解
K. 2018
Given a, b, c, d, find out the number of pairs of integers (x, y) where a x b, c y d and x y is a multiple of 2018.
Input
The input consists of several test cases and is terminated by end-of-file. Each test case contains four integers a, b, c, d.
Output
For each test case, print an integer which denotes the result.
Constraint
• 1 a b 109, 1 c d 109
• The number of tests cases does not exceed 104.
Sample Input
1 2 1 2018
1 2018 1 2018
1 1000000000 1 1000000000
Sample Output
3
6051
1485883320325200
题解:
这道题的思路虽说很简单就是找在两个范围中分别取两个点并使他们的积是2018的倍数,重要的是要理解最后消去重复点的方法。
我们可以通过题目知道只要寻找两个范围中1009和2018的个数了,因为2018的约数只有1,2,1009,2018。一个范围中1009的个数乘以另一个范围中偶数的个数即是一部分2018的倍数的个数,还有种情况是一个范围中2018的个数乘以另一个范围中数字的个数即使一部分2018的倍数的个数,用同样的方法求另一个范围中的2018的倍数然后再加起来。
这样算出来可能有重复解,1009×2018,2018×2018,2018×1009.
AC代码:
#include <stdio.h> #include <string.h> long long fw(int x, int y) { if(x%2 != 0 && y%2 != 0) { return (y-x)/2; } else if(x%2 == 0 && y%2 == 0) { return ((y-x)/2)+1; } else { return (y-x+1)/2; } } int main() { long long a, b, c, d; while(scanf("%lld%lld%lld%lld", &a, &b, &c, &d) != EOF) { long long f1, f2; f1 = 0, f2 = 0; f1 = fw(a, b); f2 = fw(c, d); long long temp, ans; ans = 0; long long a18 = 0, a19 = 0; a18 = b/2018 - (a-1)/2018; ans += a18*(d-c+1); a19 = b/1009 - (a-1)/1009 - a18; ans += a19*f2; long long a28 = 0, a29 = 0; a28 = d/2018 - (c-1)/2018; ans += a28*(b-a+1); a29 = d/1009 - (c-1)/1009 - a28; ans += a29*f1; printf("%lld\n", ans-(a19*a28+a18*(a29+a28))); } return 0; }