URAL 1139 City Blocks(数论)

The blocks in the city of Fishburg are of square form. N avenues running south to north and Mstreets running east to west bound them. A helicopter took off in the most southwestern crossroads and flew along the straight line to the most northeastern crossroads. How many blocks did it fly above?
Note. A block is a square of minimum area (without its borders).

Input

The input contains N and M separated by one or more spaces. 1 < NM < 32000.

Output

The number of blocks the helicopter flew above.
 
思路:令n = n -1, m = m - 1
考虑n或m只有1的情况,不妨设m=1,那么图形就变成了一个n个小正方体拼在一起的长方体,显然答案为n,因为灰机穿过了n个街区,我们可以认为,每穿过一条竖线,就会多穿过一个街区(包括第一条竖线,不包括最后一条竖线)。
那么当n,m>1的时候,也是每穿过一条竖线,多穿过一个街区,每穿过一条横线,多穿过一个街区。但是答案却不是n+m。
因为当灰机穿过一个整点(横纵坐标均为整数)的时候,同时穿过横线和竖线,多穿过的街区是一样的。
对于灰机的路线来讲,穿过的整点数为gcd(n, m)(不算最后一个)
第一个穿过的整点为(1,1),第二个为(n/gcd, m/gcd),第三个为(n/gcd*2, m/gcd*2)……最后一个为(n/gcd*(gcd-1), m/gcd*(gcd-1))。一共gcd个。
那么n+m减掉穿过整点的时候重复加上的街区,则答案为n+m-gcd(n,m)
 
代码(0.171S):
1 from fractions import gcd
2 n, m = map(int, raw_input().split(' '))
3 print n + m - gcd(n - 1, m - 1) - 2
View Code
原文地址:https://www.cnblogs.com/oyking/p/3575427.html