Just about primes (fast incremental method for calculating primes)

Once you seriously thought what is minimally necessary to calculate a sequence of primes from the first to N? We take everything we need and discard unnecessary - the recipe for a successful strategy. In this case, it is necessary to take into service all fast operations and discard all labor-intensive ones, like division. And the one who decided to describe prime numbers through division operations seems to have played a trick on humanity. Millennia passed, and people still continue to share ...


First code:


public HashMap<Long, Long> serialPrimes() {
   long range = Long.parseLong(this.range.getText().toString());
   HashMap<Long, Long> primes = new HashMap<>(); //    
   HashMap<Long, ArrayList<Long>> spectres = new HashMap<>(); //     
   HashMap<Long, ArrayList<Long>> toppings = new HashMap<>(); //      
   for(long i = 2; i < range; i++){
       if(toppings.keySet().contains(i)) { //      ,     i
           //  
           ArrayList<Long> spectre = toppings.get(i);
           spectres.put(i, spectre);
           toppings.remove(i);
           for(long spectreValue : spectre) {
               //      
               long topping = primes.get(spectreValue) + spectreValue;
               primes.put(spectreValue, topping);
               //    
               if(toppings.keySet().contains(topping)) {
                   toppings.get(topping).add(spectreValue);
               } else {
                   ArrayList<Long> newSpectre = new ArrayList<>();
                   newSpectre.add(spectreValue);
                   toppings.put(topping, newSpectre);
               }
           }
       } else { //      ,     i
           //   
           primes.put(i, i + i); //       ,   
   //   
           //     
           ArrayList<Long> newSpectre = new ArrayList<>();
           newSpectre.add(i);
           toppings.put(i + i, newSpectre);
       }
   }
   return primes;
}

Now an explanation.


, .


API P2P .


, -.


3 :



:


  • , 2 ()
  • T
  • ,
  • 2*n (, 2[4])
  • 4[2]
  • ,
  • ( , )

, .


1.500.000. , 2 . -, 3.000.000. 96 , 14 ( , ).


In the range from 2 to 3.000.000 lies 216.816 primes.


Android example


PS: Despite the slowness of operations, the ranges of primes are calculated by the sieve of Eratosthenes or just check individual numbers for simplicity. But when their complete sequence is needed, then it is necessary to think in approximately the same vein as described above.
But the sieve still iterates over all the numbers, trying to divide the tested number into them. Its only “advantage” is that it does not waste memory on storing intermediate calculations. But, perhaps, it takes more time to check one number than finding all the previous primes by this algorithm.


All Articles