gpt4 book ai didi

java - 幸运数字程序未显示正确答案

转载 作者:行者123 更新时间:2023-12-01 12:04:15 25 4
gpt4 key购买 nike

我正在使用普通数组制作一个幸运数字程序,以便列表中的其余数字不会向前移动。我遵循的模式是 1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93 ,99,...了解更多信息:Lucky Numbers

这是我制作的程序:

public class LuckyNumbers {

public static void main(String[] args) {
int[] lucky = new int[101];

for (int a = 0; a < lucky.length; a++){
lucky[a] = a;
}
//goes through each element in list
for (int b = 2; b < lucky.length; b++){
//checks if number is surviving
if (lucky[b] != 0){
/* if it does survive, go through the list deleting elements
* (setting them to zero) that fall on the
* index of the multiples of the the surviving number*/
int luckyNum = lucky[b]; // so that the number doesn't change
for (int c = 1; c < lucky.length;c++){
int d = luckyNum * c;
if (d < lucky.length){
lucky[d] = 0;
continue;
}
}
}
}

for (int f = 0; f < lucky.length; f++){
if (lucky[f] != 0){
System.out.println(lucky[f]);
}
}
}
}

输出是1。我认为这是一个逻辑错误。

最佳答案

问题出在代码的这一部分:

for (int c = 1; c < lucky.length;c++){
int d = luckyNum * c;
if (d < lucky.length){
lucky[d] = 0;
continue;
}
}

当您查看 wiki 页面时,您必须删除所有第 c 个幸存数字。你正在消除每一个倍数。因此,对于数字 3,您应该消除 5, 11, 17 ... 而不是 3, 6, 9... 您现在正在做的事情。

关于java - 幸运数字程序未显示正确答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27754892/

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