How to create the most compact mapping n → isprime(n) up to a limit N?

后端 未结 30 3214
遇见更好的自我
遇见更好的自我 2020-11-22 02:11

Naturally, for bool isprime(number) there would be a data structure I could query.
I define the best algorithm, to be the algorithm that pr

30条回答
  •  粉色の甜心
    2020-11-22 02:52

    Smallest memory? This isn't smallest, but is a step in the right direction.

    class PrimeDictionary {
        BitArray bits;
    
        public PrimeDictionary(int n) {
            bits = new BitArray(n + 1);
            for (int i = 0; 2 * i + 3 <= n; i++) {
                bits.Set(i, CheckPrimality(2 * i + 3));
            }
        }
    
        public PrimeDictionary(IEnumerable primes) {
            bits = new BitArray(primes.Max());
            foreach(var prime in primes.Where(p => p != 2)) {
                bits.Set((prime - 3) / 2, true);
            }
        }
    
        public bool IsPrime(int k) {
            if (k == 2) {
                return true;
            }
            if (k % 2 == 0) {
                return false;
            }
            return bits[(k - 3) / 2];
        }
    }
    

    Of course, you have to specify the definition of CheckPrimality.

提交回复
热议问题