Problem Description
YY 小时候性格孤僻,小朋友们都不喜欢跟他一起玩,于是他养成了一个奇怪的习惯:每天都在屋子里走来走去。有一天,他突然想到了一个问题,假设屋子是一个N x M 的矩形,里面铺着 1 x 1 的地板砖(即共有 N 行,每行 M 块地板砖),他想知道沿着对角线从左上角走到右下角会走过多少块地板砖( YY 可以看做一个质点)。样例中四组数据的对应图片如下图所示:
Input
输入数据的第一行为一个正整数 T(T ≤ 100),代表共有 T 组测试数据。
对于每组测试数据:
输入两个正整数 N 和 M (1 ≤ N, M ≤ 104)。
Output
对于每组测试数据,输出一个正整数 R,表示走过的地板砖数。
Sample Input
4
4 1
3 2
4 2
4 4
Sample Output
4
4
4
4
code:
import java.util.*;
public class Main {
private static int line(int n,int m,int x){
return n*x/m;
}
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
int t = cin.nextInt();
while(t-- != 0){
int n = cin.nextInt();
int m = cin.nextInt();
int res = 0;
for(int j = 1; j < m; j++){
res += (int)line(n,m,j); // 斜线到底部的距离取整,获取没有走到的格子数
}
System.out.println(m*n-res*2); // 斜线两边对称
}
cin.close();
}
}