【发布时间】:2019-03-26 09:42:24
【问题描述】:
任何人都可以帮助我使用带有 java8 的扫描仪确定所有小于给定输入值的素数。
输入:N个整数> 0
输出:带有素数的表格。
示例:对于 N = 10,输出为:2 3 5 7
这是我目前的工作:
class Main {
public static void main(String[] args) {
int N;
int[] result = null;
try (Scanner scanner = new Scanner(new File(args[0]))) {
N = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < (N/2)+1; i++) {
if (N%i==0)
result[i]=i;
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
}
System.out.println();
}
catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
}
【问题讨论】:
-
你可以使用prime sieve。
-
en.wikipedia.org/wiki/Primality_test,如果你真的想做一个算法,在这里你可以选择你喜欢的方法。老实说,它认为存储一个所有初选数低于 10000 的数组会更容易,并在你的函数中返回该数组的一部分。
-
为什么从零开始
i,为什么到N/2? -
@khelwood 我不能用 java 写它!
-
@N8888 不重复