gpt4 book ai didi

java - Java 之谜 - Java

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:17 28 4
gpt4 key购买 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.length; 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.length; i++) {
boxes[i] = i;
}

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

最佳答案

它有非常简单的解决方案

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/

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