public class BitSetPrime { public static void main(String[] args) { BitSet p=new BitSet(2000000); p.flip(2,2000000); //Considering all numbers to be prime except 0 and 1 for(int i=2 ;i<2000000;i++) { if(!p.get(i)) continue; else // Set all multiples as not prime for(int j = 2*i; j < 2000000; j += i) p.set(j,false); } long sum=0; for(int i = 2; i < 2000000; ++i) if( p.get(i) ) // Add all nos with bit set sum += i; System.out.println(sum); } }