Home > OS >  Get numbers that cannot be divided by anything
Get numbers that cannot be divided by anything

Time:12-05

how can I use Java to find out numbers that can't be divided by any other number?

i have an int array:

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. 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.

How exactly do I get to program this?

Thanks in advance!

CodePudding user response:

Like @Selvin said in the comments, these numbers have a name, they are called "prime numbers".

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;     
    }  
 } 

CodePudding user response:

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;
} 
  • Related