欧几里得算法,即辗转相除法
package demo2;
public class P95 {
//欧几里得算法,即辗转相除法
//一种变体是找线段上的格点数
public static void main(String[] args) {
//(1,11)和(5,3)两点间的线段
int x1=1;
int y1=11;
int x2=5;
int y2=3;
System.out.println("格点数:"+cellPoint(x1,y1,x2,y2));
}
//求|x1-x2|和|y1-y2|的gcd,也就是横纵最多都能分的段数,段数-1得格点数
static int cellPoint(int x1, int y1, int x2, int y2) {
int m=Math.abs(x1-x2);
int n=Math.abs(y1-y2);
return gcd(m, n)-1;
}
static int gcd(int m,int n) {
return n==0? m:gcd(n, m%n);
}
}

浙公网安备 33010602011771号