Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on.
Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-th one. That is, he'll paint bricks x, 2·x, 3·x and so on red. Similarly, Floyd skips y - 1 consecutive bricks, then he paints the y-th one. Hence he'll paint bricks y, 2·y, 3·yand so on pink.
After painting the wall all day, the boys observed that some bricks are painted both red and pink. Iahub has a lucky number a and Floyd has a lucky number b. Boys wonder how many bricks numbered no less than a and no greater than b are painted both red and pink. This is exactly your task: compute and print the answer to the question.
The input will have a single line containing four integers in this order: x, y, a, b. (1 ≤ x, y ≤ 1000, 1 ≤ a, b ≤ 2·109, a ≤ b).
Output a single integer — the number of bricks numbered no less than a and no greater than b that are painted both red and pink.
2 3 6 18
3
Let's look at the bricks from a to b (a = 6, b = 18). The bricks colored in red are numbered 6, 8, 10, 12, 14, 16, 18. The bricks colored in pink are numbered 6, 9, 12, 15, 18. The bricks colored in both red and pink are numbered with 6, 12 and 18.
大致题意是找出a到b中既能被x整除又能被y整除的数的个数
一般想法是从a扫到b,如果 (i mod a == 0 && i mod b == 0) ,那么计数器加一
但是可以看到数据范围给得很大,a和b的差值可能高达2×10^9,这样的话TLE是显然的╮(╯▽╰)╭
我的想法是找出a和b的最小公倍数LCM(a, b)
假设x为大于等于a的最小的LCM(a, b)的倍数
用b-x除LCM(a, b)就是满足条件的整数的个数
至于其它细节么,仔细处理就行了
代码如下:
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
int x, y;
long long a, b, cnt = 0;
cin >> x >> y >> a >> b;
long long mul = x*y;
for (int i = max(x,y); i <= x*y; i++)
if (i%x == 0 && i%y == 0) { mul = i; break; }
//cout << mul << endl;
long long pos;
if (a%mul == 0) pos = a;
else pos = (a/mul+1)*mul;
if (pos > b) cnt = 0;
else cnt = (b-pos)/mul+1;
cout << cnt << endl;
return 0;
}