码迷,mamicode.com
首页 > 其他好文 > 详细

codeforces The Wall - 题解

时间:2014-06-03 04:51:05      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   a   

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 123 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 xxx and so on red. Similarly, Floyd skips y?-?1 consecutive bricks, then he paints the y-th one. Hence he‘ll paint bricks yyy and 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.

Input

The input will have a single line containing four integers in this order: xyab. (1?≤?x,?y?≤?10001?≤?a,?b?≤?2·109,a?≤?b).

Output

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.

Sample test(s)
input
2 3 6 18
output
3

这是一道简单题,也隔了一段时间没做简单题目了。

这次感觉又不一样了,可以很快就能写出很优雅的代码了,故此很想贴贴自己的代码。


优雅代码的关键就是要利用数学的思想去解:

本题的实质是可以转化为求最大公倍数的的问题,然后利用Inclusion-exclusion(包含和不包含)的原则,计算有多少个数能被a除尽这个公倍数,有多少个数能被b除尽这个公倍数,然后相减就得到最终答案了。

#include <stdio.h>
using namespace std;

int TheWallGCD(int a, int b)
{
	while (b)
	{
		int t = b;
		b = a % b;
		a = t;
	}
	return a;
}

void TheWall340A()
{
	int x, y, a, b;
	scanf("%d %d %d %d", &x, &y, &a, &b);
	
	int r = TheWallGCD(x, y);
	r = x / r * y;

	int m = a % r? 0 : 1;

	printf("%d", b / r - a / r + m);
}



codeforces The Wall - 题解,布布扣,bubuko.com

codeforces The Wall - 题解

标签:c   style   class   blog   code   a   

原文地址:http://blog.csdn.net/kenden23/article/details/27544033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!