sách gpt4 ai đã đi

Java - Bí ẩn Java - Java

In lại 作者:塔克拉玛干 更新时间:2023-11-03 03:50:17 34 4
mua khóa gpt4 Nike

我的 friend 给了我一个谜语让我解开。它是这样的:

There are 100 people. Each one of them, in his turn, does the following:

The first person opens all the boxes. The second person change the state to all the boxes whose number is divided by 2, without remainders. For instance, if a box is open and its number is divided by 2, it is closed. The same goes for a closed box.

The third person change the state to all the boxes whose number is divided by 3, without remainders. The "i" person change the state to all the boxes whose number is divided by i, without remainders.

Now, at then end of the process, I need to display all the boxes(their numbers) who are open.

我尝试实现一个解决方案,但我认为它效率不高。在这里:

public class BoxesExc {

public static void main(String[] args) {
Box[] boxes = new Box[100];
// Inflating the array with boxes
for(int i=0; i
boxes[i] = new Box(i, false);
}

// Main part:
for(int i=1; i<=boxes.length; i++) {
for(int j=1; j<=i; j++) {
// If the number is even
if(i%2 == 0) {
if(j%i == 0) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
// If the number is odd
else {
if(j%2 != 0) {
if(j%i == 0) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
}
}
}

//Displaying the opened boxes:
for(Box box : boxes) {
if(box.isOpen)
System.out.println(box.getNum()+",");
}
}

public static class Box {
private int num;
private boolean isOpen;

public Box(int num, boolean isOpen) {
this.isOpen = isOpen;
}

public int getNum() {
return num;
}

public boolean isOpen() {
return isOpen;
}

public void setOpen(boolean isOpen) {
this.isOpen = isOpen;
}

}
}

我还没有尝试过,但我只是看着它,它看起来很糟糕。我需要你们的帮助来找到更好的解决方案。

编辑:好的伙计们,我设法解决了这个问题。这是解决方案:

public class BoxesExc {

public static void main(String[] args) {
int[] boxes = new int[101];
// Inflating the array with boxes
for(int i=1; i
boxes[i] = i;
}

int counter = 0;
for(int i=1; i
for(int j=1; j<=i; j++) {
if(i%j == 0)
phản++;
}
if(counter%2 != 0)
System.out.print(""+i+", ");
counter = 0;
}
}
}

1 Câu trả lời

它有非常简单的解决方案

the boxes which will be opened will be all the boxes which thier place is square exponentiation of a number.

例如,在您的问题中,它介于 1-100 之间,因此答案将是:

1 4 9 16 25 36 49 64 81 100

而且我的解决方案比你的快,因为它的顺序是 θ(√n)

关于java - Java 之谜 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27385418/

34 4 0
Bài viết được đề xuất: java - 字符串条件检查
Bài viết được đề xuất: Java 到 EDI 转换的 Java 库
Bài viết được đề xuất: java - 在 View 中发现重复的组件 ID
Bài viết được đề xuất: algorithm - 这个问题可以用动态规划解决吗?
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com