南郵離散實驗三(JAVA)

想要一隻肥宅快樂獸發表於2020-12-23

內容:編寫程式實現整除關係這一偏序關係上所有蓋住關係的求取,並判定對應偏序集是否為格。
要求:對任意給定正整數,利用整除關係求所有由其因子構成的集合所構成的格,判斷其是否為有補格。

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();
    }


}

測試結果:
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

相關文章