Prime number algorithm only works for the first verified number

Asked

Viewed 498 times

1

I created a program to check primes and in it I receive n entries. That is to say, n is the number of test cases. The problem is that in the first test case everything works fine. Already in the second the program is wrong to say if 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?

1 answer

4


The counter startup is in the wrong place, every time you check a new number, the counter has to be reset. I took advantage and made an optimization not to waste time when he already knows that 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");
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, bigown!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.