[英]Get numbers that cannot be divided by anything
how can I use Java to find out numbers that can't be divided by any other number?如何使用 Java 找出不能被任何其他数字除的数字?
i have an int array:我有一个 int 数组:
int[] numbers = new int[25];
Now I want to iterate over this array and output all the numbers that are not divisible in a new array.现在我想遍历这个数组和 output 所有在新数组中不可整除的数字。 The remaining numbers should no longer appear in the new array.
剩余的数字不应再出现在新数组中。
For example, in a range from 1-25, only the numbers [1,3,5,7,11,13,17,19,23] should be output as an array.例如,在 1-25 的范围内,只有数字 [1,3,5,7,11,13,17,19,23] 应该是 output 作为数组。
How exactly do I get to program this?我究竟该如何编程?
Thanks in advance!提前致谢!
Like @Selvin said in the comments, these numbers have a name, they are called "prime numbers".就像@Selvin 在评论中所说,这些数字有一个名字,它们被称为“素数”。
For example, you can use something like this:例如,您可以使用如下内容:
for (int number : numbers) {
if (!primeCal(number)) {
number = null;
}
}
private static void primeCal(int num) {
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
You must first iterate and then use the following method to check if any of them are prime numbers or not您必须首先迭代,然后使用以下方法检查它们中的任何一个是否为素数
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.