Effecient Use Sieve of Eratosthenes algorithm Given this as a the Problem Statement 


  Given two numbers, find the sum of prime numbers between them, both
  inclusive.
  
  Input:
  
  The first line contains the number of test cases T. Each test case
  contains two space separated integers.
  
  Output:
  
  Print the answer on a new line for each case.
  
  Constraints:
  
  1 &lt;= T &lt;= 100
  
  1 &lt;= a,b &lt; 10^6


. Here is the working code of mine, that has been accepted.

class TestClass {

    public static void main(String args[] ) throws Exception {
        BufferedReader keyboard= new BufferedReader(new InputStreamReader(System.in));
        int t=Integer.parseInt(keyboard.readLine());

        while(t&gt;0 &amp;&amp; t&lt;=100){
            String[] tempInt=keyboard.readLine().split(" ");
            int n=Integer.parseInt(tempInt[0]);
            int m=Integer.parseInt(tempInt[1]);

            int sum=primeSum(n,m);
            System.out.println(sum);
            t--;
        }
    }

private static int primeSum(int n, int m) {
        int sum=0;
        int maxFactor= (int)Math.sqrt(m);
        boolean[] isPrime=new boolean[m + 1];
        int len=isPrime.length;
        Arrays.fill(isPrime,true);
        isPrime[0]=false;
        isPrime[1]=false;
        for(int i=0;i&lt;=maxFactor;i++){
            if(isPrime[i]){
                for(int j=i+i;j&lt;len;j+=i){
                    isPrime[j]=false;
                }
            }
        }
        for(int i=n;i&lt;=m;i++){
            if(isPrime[i]){
                sum=sum+i;
            }
        }
        return sum;
    }

}


But what is really bugging me is this line boolean[] isPrime=new boolean[m + 1];. Where i Have to use really large block of space. How could i avoid such large allocation while being effiecient too.? What are futher way of improvement of this code apart from array allocation ?
Ways to decrease the allocation
Since your main question was about the allocation length, I'll suggest two ways to decrease the allocation (although 1 MB really isn't that much to begin with).

Since the only even number that is prime is 2, you can only allocate half the amount by only considering odd numbers.  When you perform the sieve, you skip all even numbers and use index [j/2] for each odd number.  Just remember at the end to count 2 as one of the primes if the range includes it.

You can use 1 bit per number instead of 1 boolean per number.  You can use BitSet or your own bit array.


Combining both of the above allows you to allocate 1/16 the amount that you originally allocated (so about 64KB instead of 1MB).  I don't think it will help at all though.  If anything, your program will only get slower.
Reuse the allocation
Also, since you are running up to 100 test cases, you might as well just run the sieve once on the maximum input (10^6).  Then you can compute the 100 answers quickly without redoing all the work each time.