-3

Once I took from the user 10 numbers and placed them in an array of size 10, I want to check for each number in the array if it is prime or not and count how many prime numbers there is. Here is what I tried to do:

int count=0;
for(int r=0;r<10;r++) {
    for(int t=2; t < array[r];t++) {
        if(array[r] % t != 0) {
            count++;
        }
    }
}

array[r] is already filled with numbers at this point, so all I need to do is to check for each number if it is prime or not.

JNYRanger
  • 6,829
  • 12
  • 53
  • 81

2 Answers2

0

Here is another way you can check for prime numbers. It does not increment by 1, so it is faster.

int count=0;
for(int r=0;r<10;r++){
    if (isPrime(array[r])) count++;
}

And the method:

public static boolean isPrime(int n) {
    if(n < 2) return false;
    if(n == 2 || n == 3) return true;
    if(n%2 == 0 || n%3 == 0) return false;
    int sqrtN = (int)Math.sqrt(n)+1;
    for(int i = 6; i <= sqrtN; i += 6) {
        if(n%(i-1) == 0 || n%(i+1) == 0) return false;
    }
    return true;
}
gonzo
  • 2,103
  • 1
  • 15
  • 27
-1
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    int count=a.length;
    boolean flag=true;
    for(int i=0;i<a.length;i++)
    {
        for(int j=2;j<a[i];j++)
        {
            if(a[i]%j==0)
            {
                flag=false;
                break;
            }
        }
        if(flag==false)
        {
            count--;
        }
    }
    System.out.println(count);
  • 1
    `boolean flag=true;` must be inside the first loop – Maurice Perry Oct 01 '21 at 08:25
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 01 '21 at 08:27