内容:编写程序实现整除关系这一偏序关系上所有盖住关系的求取,并判定对应偏序集是否为格。
要求:对任意给定正整数,利用整除关系求所有由其因子构成的集合所构成的格,判断其是否为有补格。
import java.util.Scanner;
public class Pianxu {
private static int n; //正整数n
private static int count = 0; //计数
private static int[] factors = new int[100]; //存放因子
private static int[][] matrixs = new int[100][100];
public static int gcd(int x, int y) {
int m = 1;
while (m != 0) {
m = x % y;
x = y;
y = m;
}
return x;
}
public static void factor(int n) {
for (int i = 1; i <= n/2; i++) {
if (n % i == 0) {
factors[count] = i;
count++;
System.out.print(i + ",");
}
}
// count++;
factors[count] = n;
System.out.println(n);
}
public static void cover() {
for (int i = 0; i <= count; i++) {
for (int j = 0; j <= count; j++) {
//满足整除关系设为1
matrixs[i][j] = ((factors[j] % factors[i] == 0) ? 1 : 0);
}
}
for (int i = 0; i <= count; i++) {
for (int j = 0; j <= count; j++) {
for (int k = 0; k <= count; k++) {
matrixs[k][k] = 0; //去掉自反性
if (matrixs[i][j] == 1 && matrixs[j][k] == 1) {
matrixs[i][k] = 0;
}
}
}
}
System.out.print("盖住关系{");
for (int i = 0; i <= count; i++) {
for (int k = 0; k <= count; k++) {
if (matrixs[i][k] == 1) {
System.out.print("<" + factors[i] + "," + factors[k] + ">");
}
}
}
System.out.println("}");
}
//判断补格
public static void lattice() {
int gcd;
int lcm;
boolean flag;
for (int i = 1; i < count; i++) {
flag = false;
for (int j = 1; j < count; j++) {
if (i == j) {
continue;
}
gcd = gcd(factors[i], factors[j]); //最大公约数,即最大下界
lcm = factors[i] / gcd * factors[j]; //最小公倍数,即最小上界
if (gcd == factors[0] && lcm == factors[count]) {
//最大下界为1,最小上界为n
flag = true;
break;
}
}
if (!flag) {
System.out.println("不是有补格");
return;
}
System.out.println("是有补格");
return;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个正整数");
n = sc.nextInt();
System.out.println();
factor(n);
cover();
lattice();
}
}
测试结果: