我需要程序来查找素数并将它们放入数组中并返回它们。我只想在 Main 类中使用 System.out 。我应该在我的代码中添加什么?谢谢。
这是我在第一个类中查找哪些数字是质数的第一个方法:
private boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0)
return false;
}
return true;
}
这是我需要帮助的另一种方法:
public int[] test(int a, int b) {
//what do I write here
for (int i = a; i <= b; i++) {
if (isPrime(i)) {
//what do I write here, I only want to use syso in the other
//class(Main).
}
}
return ?;
}
这是我的主要类(class):
public static void main(String... args) {
Prime p = new Prime();
System.out.println(p.test(10, 30));
}
最佳答案
将数字放入列表中并将其转换为 int 数组:
public int[] test(int a, int b) {
List<Integer> result = new ArrayList<>();
//what do I write here
for (int i = a; i <= b; i++) {
if (isPrime(i))
result.add(i);
//what do I write here, I only want to use syso in the other
//class(Main).
}
return result.stream()
.mapToInt(Integer::intValue)
.toArray();
}
关于java - 求一定范围内的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74294210/