Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a new array of primes from a random array?

Hy there i a beginner in java started 3 weeks ago, im having some problems with this code.

in the main method i have an array containing 10 elements. i've already made several methods to like

public static void println(int[] array) ------ to print and array

public static boolean isPrime(int el) ----------- prime test. returns true or false

public static int countPrimes(int[] array) --- returns back the number of primes in the array.

this is the array

int[] array = new int{7,5,7,2,11,-4,5,,10,2}

the method im having problems with is:

public static int[] primesInArray(int[] array)
  {
   int n = array.length;
   int[] temp = new int[countPrimes(array)];  
   int j = 0;

   for(int i = 0; i < n; i++)
     {
       if(isPrime(array[i]))
       { 
         temp[j] = array[i];
         j= j +1;
       }
     }
     return temp;
  }

it should return an array of 7 numbers like this {7,5,7,2,11,5,2} but instead i get the original array back.

what am i doing wrong.

like image 954
Carlos B. Avatar asked Jan 28 '26 20:01

Carlos B.


1 Answers

What is the purpose of this test?

if(array[i] % array[i] == 0 || array[i] % array[i] == 1)

array[i] % array[i] will always be 0 so your test always returns True.

Shouldn't you instead use the following?

if (isPrime(array[i]))

Edit: And as Ravi points out, you don't ever use your temp array! I think you need to change array[i] = array[j]; to temp[j] = array[i]; when the corrected if test is True.

like image 167
sam Avatar answered Feb 01 '26 01:02

sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!