title: How to optimize Prime Number generator in java?
body: <p>I was doing some question on SPOJ and it is called prime number generator.</p>
  
  <p>My code is working fine on my local machine but on SPOJ i'm getting error of time limit exceeded .</p>
  
  <p>Can someone please tell me how can i make this program and programs of similar kinds with have a lot of nested loop run more efficiently?</p>
  
  <pre><code>  import java.util.*;
    import java.lang.*;
    import java.math.*;
  
    class Main {
       public static void main (String[] args) throws java.lang.Exception {
          Scanner obj = new Scanner(System.in);
          int t = obj.nextInt();
  
          for(int i = 0; i &lt; t; i++) {
             int m = obj.nextInt();
             int n = obj.nextInt();
  
             for(int x = m; x &lt;= n; x++) {
                boolean flag = true;
                int count = 0;
                for(int j = 2; j &lt; Math.pow(n,0.5) ; j++) {
                   if(x == 1 || x == 2) {
                      flag = false;
                      break;
                   }
                   if(x % j == 0 &amp;&amp; x != j) {
                      flag = false;
                      break;
                }
             }
             if(flag) {
                System.out.println(x);
             }
          }
          System.out.println();
       }
    }
  </code></pre>