gpt4 book ai didi

java - 互质数矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:57 25 4
gpt4 key购买 nike

我想创建一个 NxN 矩阵,从命令行矩阵中获取 N,使得如果 i 和 j 相对,则第 i 行 j 列 (1 ≤ i, j ≤ N) 中的元素是“*”(星号)素数(即 GCD(i, j) = 1),否则为“”(空格)。行号应该是打印在每行的末尾。

public static boolean[][] relativelyPrime(int N) {
boolean[][] array = new boolean [N+1][N+1];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if ( 1 <= i && i <= N && 1 <= j && j <= N) {
if (gcd(i,j) == 1){
return array;
}
}
}
}
return array;
}

public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
boolean[][] matrix = relativelyPrime(N);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length: j++) {
if (1 <= i && i <= N && 1 <= j && j <= N) {
if (gcd(i, j) == 1) { System.out.println("*" + i);
}
else { System.out.println(" " + i);
}
}
}
}

我正在尝试创建一个如下所示的矩阵:

* * * * * * * * * * 1
* * * * * 2
* * * * * * * 3
* * * * * 4
* * * * * * * * 5
* * * 6
* * * * * * * * * 7
* * * * * 8
* * * * * * * 9
* * * * 10

但我得到

*1
*1
*1
*1
*1
*1
*1
*1
*1
*1
*2
2
*2
2
.
.
.

如何将其放入矩阵

最佳答案

您应该使用 System.out.print 而不是 System.out.println,如下所示:

    public static void main(String[] args) {
int N = 11;
boolean[][] matrix = relativelyPrime(N);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (1 <= i && i <= N && 1 <= j && j <= N) {
if (gcd(i, j) == 1) { System.out.print("*");
}
else { System.out.print(" ");
}
}
}
System.out.println(i);
}
}

在这种情况下,它会在第一行给你零,为了消除这种情况,请使用附加的 if 语句:

         }
if(i!=0)
System.out.println(i);
}

关于java - 互质数矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com