Posts

Search

Primality Testing - II 1

You are given Q different queries. Each query consists of one number each i.e. N.
You are to write a program that, for each query tests whether the number is prime or not.
You must output Q different lines to stdout, ith line being "yes" if the N for ith query is a prime number and "no" otherwise.
Input Format
First line contains one integer, the number of queries Q.
Next Q lines contain one integer each, the N for the queries.
Constraints
1 <= Q <= 5x10^6
1 <= N <= 5x10^6
Output Format
Output Q lines, on each line you must print "yes" or "no" depending on the primality of the N in the query.
Sample Input 0
5
1
2
3
4
5
Sample Output 0
no
yes
yes
no
yes
SOLUTION :-


import java.io.*;
import java.util.*;

public class Solution {
    static int ar[]=new int[5000002];
    static void precal()
    {
        ar[0] = 1;
        ar[1] = 1;
        for (long p=2; p*p<=5000001; p++)
        {
            if (ar[(int)p] == 0)
            { 
                for (long i=p*p; i<=5000001; i += p)
                    ar[(int)i] = 1;
            }
        }
    }
    public static void main(String[] args) throws IOException
    {
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out),"ASCII"), 512);
     
        BufferedReader br = new BufferedReader(
                              new InputStreamReader(System.in));
        int t=Integer.parseInt(br.readLine());
        precal();
        while(t-->0)
        {
            int a=Integer.parseInt(br.readLine());;
            if(ar[a]==0)
            {
                out.write("yes\n");
            }
            else
            {
                out.write("no\n");
            }
        }
        out.flush();
     
    }
}