TÓPICO

How can I solve "Time Limit Excite"

PedoroKisen perguntou 2 years ago

I'm facing a Time limit exceeded problem. Then I update my code with recursion. Also, it shows the same problem. Below is my first code when I wrote it.

My Code :


import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int i, num, limit;
        byte j, p;     
        limit = in.nextInt();

        for (j=1; j<=limit;  j++){
            p=0;
            num = in.nextInt();
            for (i=2; i<num; i++){
                if (num % i == 0) {
                    p = 1;
                    break;
                }
            }
              if (p == 1) System.out.printf ("Not Prime\n");
              else  System.out.printf ("Prime\n");
        }
    }
}

Lembre de não publicar soluções. Sua publicação pode ser revisada por nossos moderadores.

  • GabrielBento respondido 2 years ago

    In this question we need an algorithm fast, if it insn't this problem (time exceeded) happens. I recommend you search an algorithm called O(sqrt(n)).