Algorithm of prime numbers only works for the first verified number

1

I have created a prime number verification program and receive n entries in it. That is, n is the number of test cases. The problem is that in the first test case everything works fine. Already in the second onwards the program errs in saying whether the number is prime or not.

    import java.util.Scanner;
    public class Main {
    public static void main(String [] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int contador = 0;

    for(int i = 1; i <= n; i++){
        int v = sc.nextInt();

        for(int j = 1; j <= v; j++){
            if(v % j == 0){
                contador++;
            }
        }
        if(contador == 2){
            System.out.println("PRIME");
        }
        else{
            System.out.println("NOT PRIME");
        }
    }
}
}

How to fix?

    
asked by anonymous 01.07.2016 / 22:15

1 answer

3

The initialization of the counter is in the wrong place, every time a new number is checked, the counter has to be reset. I took advantage of it and did an optimization to not waste time when he already knows that he is not cousin:

import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        for (int i = 1; i <= n; i++) {
            int v = sc.nextInt();
            int contador = 0;

            for (int j = 1; j <= v; j++) {
                if (v % j == 0) {
                    contador++;
                    if (contador == 3) {
                        break;
                    }
                }
            }
            if (contador == 2) {
                System.out.println("PRIME");
            } else {
                System.out.println("NOT PRIME");
            }
        }
    }
}

See running on ideone and on CodingGround .

    
01.07.2016 / 22:22