java - Codechef "Primality Test" Wrong answer -


problem: alice , bob meeting after long time. usual love play math games. times alice takes call , decides game. game simple, alice says out integer , bob has whether number prime or not. bob usual knows logic since alice doesn't give bob time think, bob decides write computer program. bob accomplish task writing computer program calculate whether number prime or not . input

the first line of input contains t testcases, t lines follow each of t line contains integer n has tested primality output

for each test case output in separate line, "yes" if number prime else "no"

my solution:

`import java.io.*; import java.math.*; import java.util.*; class ex6 { public static void main(string args[])throws ioexception {     try     {         bufferedreader input=new bufferedreader(new inputstreamreader(system.in));               int t=0;         t=integer.parseint(input.readline());      int n=0;     int c=0;      while(c!=(t))     {         int j=0;         n=integer.parseint(input.readline());         if(n==1)         system.out.println("no");         else{             for(int x=2;x<n/2;x++)             {              if(n%x==0){j++;break;}             }             if(j==0)             system.out.println("yes");             else              system.out.println("no");         }              c++;           } }  catch(exception e)  {return;}}}` 

your whole approach wrong, read https://en.wikipedia.org/wiki/sieve_of_eratosthenes. besides, these exercises assume use known algorithm.

the idea have array boolean values, "true" means "prime" , "false" means "non-prime", start array of true boolean values (besides 1 , 0), starting 2 eliminate multiples of 2 (marking them false), move next prime number, 3, mark false multiples of that, etc, until you're done.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -