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

compact set
sequentially compact
is 0,1 compact
how to prove a set is compact
compactness definition
compact set pdf
heine-borel theorem
compact set in real analysis

Naturally, for bool isprime(number) there would be a data structure I could query. I define the best algorithm, to be the algorithm that produces a data structure with lowest memory consumption for the range (1, N], where N is a constant. Just an example of what I am looking for: I could represent every odd number with one bit e.g. for the given range of numbers (1, 10], starts at 3: 1110

The following dictionary can be squeezed more, right? I could eliminate multiples of five with some work, but numbers that end with 1, 3, 7 or 9 must be there in the array of bits.

How do I solve the problem?

There are many ways to do the primality test.

There isn't really a data structure for you to query. If you have lots of numbers to test, you should probably run a probabilistic test since those are faster, and then follow it up with a deterministic test to make sure the number is prime.

You should know that the math behind the fastest algorithms is not for the faint of heart.

How to create the most compact mapping n → isprime(n) up to a , How to create the most compact mapping n → isprime(n) up to a , Naturally, for bool isprime(number) there would be a data structure I could query. I define the  An important special case of a compact mapping is a finite-to-one mapping. Topological properties are stable most often with respect to perfect mappings, which are the most natural analogues of continuous mappings of compacta in the class of all Hausdorff spaces. A product of compact mappings is a compact mapping. References

The fastest algorithm for general prime testing is AKS. The Wikipedia article describes it at lengths and links to the original paper.

If you want to find big numbers, look into primes that have special forms like Mersenne primes.

The algorithm I usually implement (easy to understand and code) is as follows (in Python):

def isprime(n):
    """Returns True if n is prime."""
    if n == 2:
        return True
    if n == 3:
        return True
    if n % 2 == 0:
        return False
    if n % 3 == 0:
        return False

    i = 5
    w = 2

    while i * i <= n:
        if n % i == 0:
            return False

        i += w
        w = 6 - w

    return True

It's a variant of the classic O(sqrt(N)) algorithm. It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.

Sometimes, If I really want speed and the range is limited, I implement a pseudo-prime test based on Fermat's little theorem. If I really want more speed (i.e. avoid O(sqrt(N)) algorithm altogether), I precompute the false positives (see Carmichael numbers) and do a binary search. This is by far the fastest test I've ever implemented, the only drawback is that the range is limited.

Compact space, In mathematics, more specifically in general topology, compactness is a property that For any subset A of Euclidean space Rn, A is compact if and only if it is closed to the above statements, the pre-image of a compact space under a proper map is compact. Not logged in; Talk · Contributions · Create account · Log in  The compacity W p m + k → W q k is then easy to prove going back to the definition of a compact mapping and the completude of these spaces (cf. p. 487). The Kondrakov theorem does not hold if U is not bounded. For instance H 1 (R n) is not compactly embedded in L 2 (R n) [for more on compact embeddings, cf. Problem VI 6, H s,δ spaces].

The best method, in my opinion, is to use what's gone before.

There are lists of the first N primes on the internet with N stretching up to at least fifty million. Download the files and use them, it's likely to be much faster than any other method you'll come up with.

If you want an actual algorithm for making your own primes, Wikipedia has all sorts of good stuff on primes here, including links to the various methods for doing it, and prime testing here, both probability-based and fast-deterministic methods.

There should be a concerted effort to find the first billion (or even more) primes and get them published on the net somewhere so people can stop doing this same job over and over and over and ... :-)

Permutation, In mathematics, a permutation of a set is, loosely speaking, an arrangement of its members into The number of permutations of n distinct objects is n factorial, usually written This form is more compact, and is common in elementary combinatorics and Furthermore, Foata's mapping takes an n-permutation with k​-weak  Theorem 2. If f(X) = Y is a compact mapping and Y is a locally compact Hausdorff space, then f is closed and point inverses are compact. That point inverses are compact is obvious. Let F be a closed subset of X, and suppose yEf(F) and is an ac-cumulation point of/(F). Since Y is locally compact, an open set G

bool isPrime(int n)
{
    // Corner cases
    if (n <= 1)  return false;
    if (n <= 3)  return true;

    // This is checked so that we can skip 
    // middle five numbers in below loop
    if (n%2 == 0 || n%3 == 0) return false;

    for (int i=5; i*i<=n; i=i+6)
        if (n%i == 0 || n%(i+2) == 0)
           return false;

    return true;
}

this is just c++ implementation of above AKS algorithm

US7577558B2, A memory mapping system for providing compact mapping between The memory mapping system can compactly map contents from one or more first appears to be created in the processing devices by calculating the outputs of the user as compactly mapping any suitable number of first memory systems 200A-​N with  Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

I compared the efficiency of the most popular suggestions to determine if a number is prime. I used python 3.6 on ubuntu 17.10; I tested with numbers up to 100.000 (you can test with bigger numbers using my code below).

This first plot compares the functions (which are explained further down in my answer), showing that the last functions do not grow as fast as the first one when increasing the numbers.

And in the second plot we can see that in case of prime numbers the time grows steadily, but non-prime numbers do not grow so fast in time (because most of them can be eliminated early on).

Here are the functions I used:

  1. this answer and this answer suggested a construct using all():

    def is_prime_1(n):
        return n > 1 and all(n % i for i in range(2, int(math.sqrt(n)) + 1))
    
  2. This answer used some kind of while loop:

    def is_prime_2(n):
        if n <= 1:
            return False
        if n == 2:
            return True
        if n == 3:
            return True
        if n % 2 == 0:
            return False
        if n % 3 == 0:
            return False
    
        i = 5
        w = 2
        while i * i <= n:
            if n % i == 0:
                return False
            i += w
            w = 6 - w
    
        return True
    
  3. This answer included a version with a for loop:

    def is_prime_3(n):
        if n <= 1:
            return False
    
        if n % 2 == 0 and n > 2:
            return False
    
        for i in range(3, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    
  4. And I mixed a few ideas from the other answers into a new one:

    def is_prime_4(n):
        if n <= 1:          # negative numbers, 0 or 1
            return False
        if n <= 3:          # 2 and 3
            return True
        if n % 2 == 0 or n % 3 == 0:
            return False
    
        for i in range(5, int(math.sqrt(n)) + 1, 2):
            if n % i == 0:
                return False
    
        return True
    

Here is my script to compare the variants:

import math
import pandas as pd
import seaborn as sns
import time
from matplotlib import pyplot as plt


def is_prime_1(n):
    ...
def is_prime_2(n):
    ...
def is_prime_3(n):
    ...
def is_prime_4(n):
    ...

default_func_list = (is_prime_1, is_prime_2, is_prime_3, is_prime_4)

def assert_equal_results(func_list=default_func_list, n):
    for i in range(-2, n):
        r_list = [f(i) for f in func_list]
        if not all(r == r_list[0] for r in r_list):
            print(i, r_list)
            raise ValueError
    print('all functions return the same results for integers up to {}'.format(n))

def compare_functions(func_list=default_func_list, n):
    result_list = []
    n_measurements = 3

    for f in func_list:
        for i in range(1, n + 1):
            ret_list = []
            t_sum = 0
            for _ in range(n_measurements):
                t_start = time.perf_counter()
                is_prime = f(i)
                t_end = time.perf_counter()

                ret_list.append(is_prime)
                t_sum += (t_end - t_start)

            is_prime = ret_list[0]
            assert all(ret == is_prime for ret in ret_list)
            result_list.append((f.__name__, i, is_prime, t_sum / n_measurements))

    df = pd.DataFrame(
        data=result_list,
        columns=['f', 'number', 'is_prime', 't_seconds'])
    df['t_micro_seconds'] = df['t_seconds'].map(lambda x: round(x * 10**6, 2))
    print('df.shape:', df.shape)

    print()
    print('', '-' * 41)
    print('| {:11s} | {:11s} | {:11s} |'.format(
        'is_prime', 'count', 'percent'))
    df_sub1 = df[df['f'] == 'is_prime_1']
    print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
        'all', df_sub1.shape[0], 100))
    for (is_prime, count) in df_sub1['is_prime'].value_counts().iteritems():
        print('| {:11s} | {:11,d} | {:9.1f} % |'.format(
            str(is_prime), count, count * 100 / df_sub1.shape[0]))
    print('', '-' * 41)

    print()
    print('', '-' * 69)
    print('| {:11s} | {:11s} | {:11s} | {:11s} | {:11s} |'.format(
        'f', 'is_prime', 't min (us)', 't mean (us)', 't max (us)'))
    for f, df_sub1 in df.groupby(['f', ]):
        col = df_sub1['t_micro_seconds']
        print('|{0}|{0}|{0}|{0}|{0}|'.format('-' * 13))
        print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
            f, 'all', col.min(), col.mean(), col.max()))
        for is_prime, df_sub2 in df_sub1.groupby(['is_prime', ]):
            col = df_sub2['t_micro_seconds']
            print('| {:11s} | {:11s} | {:11.2f} | {:11.2f} | {:11.2f} |'.format(
                f, str(is_prime), col.min(), col.mean(), col.max()))
    print('', '-' * 69)

    return df

Running the function compare_functions(n=10**5) (numbers up to 100.000) I get this output:

df.shape: (400000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |     100,000 |     100.0 % |
| False       |      90,408 |      90.4 % |
| True        |       9,592 |       9.6 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.57 |        2.50 |      154.35 |
| is_prime_1  | False       |        0.57 |        1.52 |      154.35 |
| is_prime_1  | True        |        0.89 |       11.66 |       55.54 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        1.14 |      304.82 |
| is_prime_2  | False       |        0.24 |        0.56 |      304.82 |
| is_prime_2  | True        |        0.25 |        6.67 |       48.49 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        0.95 |       50.99 |
| is_prime_3  | False       |        0.20 |        0.60 |       40.62 |
| is_prime_3  | True        |        0.58 |        4.22 |       50.99 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.20 |        0.89 |       20.09 |
| is_prime_4  | False       |        0.21 |        0.53 |       14.63 |
| is_prime_4  | True        |        0.20 |        4.27 |       20.09 |
 ---------------------------------------------------------------------

Then, running the function compare_functions(n=10**6) (numbers up to 1.000.000) I get this output:

df.shape: (4000000, 5)

 -----------------------------------------
| is_prime    | count       | percent     |
| all         |   1,000,000 |     100.0 % |
| False       |     921,502 |      92.2 % |
| True        |      78,498 |       7.8 % |
 -----------------------------------------

 ---------------------------------------------------------------------
| f           | is_prime    | t min (us)  | t mean (us) | t max (us)  |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_1  | all         |        0.51 |        5.39 |     1414.87 |
| is_prime_1  | False       |        0.51 |        2.19 |      413.42 |
| is_prime_1  | True        |        0.87 |       42.98 |     1414.87 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_2  | all         |        0.24 |        2.65 |      612.69 |
| is_prime_2  | False       |        0.24 |        0.89 |      322.81 |
| is_prime_2  | True        |        0.24 |       23.27 |      612.69 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_3  | all         |        0.20 |        1.93 |       67.40 |
| is_prime_3  | False       |        0.20 |        0.82 |       61.39 |
| is_prime_3  | True        |        0.59 |       14.97 |       67.40 |
|-------------|-------------|-------------|-------------|-------------|
| is_prime_4  | all         |        0.18 |        1.88 |      332.13 |
| is_prime_4  | False       |        0.20 |        0.74 |      311.94 |
| is_prime_4  | True        |        0.18 |       15.23 |      332.13 |
 ---------------------------------------------------------------------

I used the following script to plot the results:

def plot_1(func_list=default_func_list, n):
    df_orig = compare_functions(func_list=func_list, n=n)
    df_filtered = df_orig[df_orig['t_micro_seconds'] <= 20]
    sns.lmplot(
        data=df_filtered, x='number', y='t_micro_seconds',
        col='f',
        # row='is_prime',
        markers='.',
        ci=None)

    plt.ticklabel_format(style='sci', axis='x', scilimits=(3, 3))
    plt.show()

Mapping luminous blue compact galaxies with VIRUS-P , Mapping luminous blue compact galaxies with VIRUS-P. Morphology, line ratios, and kinematics. L. M. Cairós1, N. Caon2,3, B. García Lorenzo2,3, A. Kelz1, M. Roth1, A significant intrinsic absorption by dust is present in all galaxies, the most The number of stars combined to create the optimal stellar template for each  A physical network map diagrams all the actual components, including cords and plugs. A logical map shows the type of network topology (bus, ring, etc.), and how the data moves and behaves logically in the network environment. A functional network map shows you how application traffic flows through the network physically.

Compact Representations for the Design of Quantum Logic, by unitary transformation matrices, i.e. complex-valuedr n×rn matrices where r is However, two observations can be made which build the basis for a compact More precisely, we observe— starting with r = 2—that a 2n × 2n matrix can be U01 corresponds to the top-right sub-matrix which describes the mapping of  Here's Part 1 of the long awaited mapping tutorial! Keep in mind this is for beginners, but that doesn't mean you can't watch it :3 Btw, this is the longest video I've ever made, guess that's a thing.

How to use Google Maps - Google Maps Help, Learn more about Google Maps COVID-19 updates. How to use Google Maps. Use Google Maps on your computer, phone, or tablet  Mapping is a very niche genre so don't expect to get lots of subscribers, views, or make lots of money from Mapping as the average mapper has only a few hundred subscribers, you should do mapping because you want to do it. Mapping Dialect . There are many different styles, genres, and dialects of Mapping.

The Century Dictionary Supplement, Coassine the small South American spike-horned deer of the genera Coassus and Pudu, with dire results to the offspring—bodies that could not make a shadow, and horns of the old by giving a small rotation backward the brake is applied; hence the name. coasting, n. 4. A surveyor engaged in mapping a coast-line. Easily create and personalize a custom map with MapQuest My Maps. Print and share your next trip or plan out your day.

Comments
  • Your request is a little vague. You give a signature that tests a single number but then ask for a data structure of (1,N]. Do you want an algorithm that generates a dictionary<int,bool> or just a one-shot function that checks if a single number is prime?
  • @Michael Sorry, that is the best description I could comeup with. What I am looking is excactly as you are saying: a boolean dictionary. I would like to minimize the space of the dictionary. Thanks :)
  • If that's what you're looking for it's been asked already: stackoverflow.com/questions/1032427/…
  • You would need to Ask the NSA
  • related: Miller–Rabin primality test in Python
  • Miller-Rabin is a popular fast probabilistic test to start out with.
  • Two questions: Can you explain better what the variables i and w are, and what is meant by the form 6k-1 and 6k+1? Thank you for your insight and the code sample (which I'm trying to understand)
  • @Freedom_Ben Here you go, quora.com/…
  • Wouldn't it be better to calculate the sqrt of n once and comparing i to it, rather than calculating i * i every cycle of the loop?
  • @Dschoni ... but you can't fit the fastest implementation in the comment fields here to share with us?
  • It fails for number 1 :(
  • @hamedbh: Interesting. Have you tried to download those files? It appears they don't exist.
  • Not yet, I'm afraid: I was just looking quickly during my lunch break. I'll delete that link in case there's anything malicious about it. So sorry, I really should have checked it first.
  • Such lists do exist. Ive seen them years ago but never cared to download them. The truth is, they take up a lot of space (relatively speaking), and shouldn't be included in programs one sells or distributes. Furthermore, they will always and forever be incomplete. It kind of does make more sense to test each number that comes up in practice during a programs use, as far fewer will be tested that way than the length of any list you might own. Also, I think pax doesnt realize the purpose of prime algorithms, most of the time, is to test efficiency/speed rather than actually finding primes.