简体   繁体   English

获取不能被任何东西除的数字

[英]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.

相关问题 生成可以除以2的随机数 - Generate random numbers that can be divided by 2 判断一个数字数组是否可以分成一组k个连续的数字 - Determine if an array of numbers can divided into a set of k consecutive numbers 无法获取已加入的Kafka流来运行或输出任何内容 - Cannot get a joined Kafka stream to run or output anything 无法从微调器菜单中获取任何更改颜色的内容 - Cannot get anything to change color from spinner menu 无法在数组中获得两个相等数字的两个位置 - Cannot get the two places of 2 equal numbers in an array 如何将今天的日期按季度划分 - How to get today's date as quarterly divided Java中的某些BigDecimal数在划分时会引发ArithmeticException - Certain BigDecimal numbers in Java when divided causes the ArithmeticException to be thrown solr无法删除任何内容 - solr cannot delete anything 确定数字数组是否可以分成两个数组,每个数组包含相同的数字总和 - Determine whether or not can an array of numbers can be divided into two arrays, with each array holding the same sum of numbers 我正在尝试通过自定义适配器使用ExpandableListView,但无法显示任何内容 - I'm trying to use ExpandableListView with a custom adapter, but cannot get anything to display
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM