Prime number calculation fun

前端 未结 18 1767
深忆病人
深忆病人 2020-12-05 15:32

We\'re having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearl

18条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 15:39

    Here is a fast and simple solution:

    • Finding primes less than 100000; 9592 were found in 5 ms
    • Finding primes less than 1000000; 78498 were found in 20 ms
    • Finding primes less than 10000000; 664579 were found in 143 ms
    • Finding primes less than 100000000; 5761455 were found in 2024 ms
    • Finding primes less than 1000000000; 50847534 were found in 23839 ms

      //returns number of primes less than n
      private static int getNumberOfPrimes(final int n)
      {
          if(n < 2) 
              return 0;
          BitSet candidates = new BitSet(n - 1);
          candidates.set(0, false);
          candidates.set(1, false);
          candidates.set(2, n);
          for(int i = 2; i < n; i++)
              if(candidates.get(i))
                  for(int j = i + i; j < n; j += i)
                      if(candidates.get(j) && j % i == 0)
                          candidates.set(j, false);            
          return candidates.cardinality();
      }    
      

提交回复
热议问题