代码之家  ›  专栏  ›  技术社区  ›  Khaled Alshaya

检查数字是否为素数的最佳算法是什么?

  •  132
  • Khaled Alshaya  · 技术社区  · 15 年前

    举一个例子,我要找的是:我可以用一个位来表示每个奇数,例如,对于给定的数字范围(1,10),从3开始:

    1110
    

    下面的字典可以压缩得更多,对吗?我可以通过一些工作消除5的倍数,但以1、3、7或9结尾的数字必须在位数组中。希望这能说明我想要什么。

    我正在寻找最佳算法,以检查一个数字是否是素数,即布尔函数:

    bool isprime(number);
    

    我想知道实现这个功能的最佳算法。当然,我可以查询一个数据结构。我 定义最佳算法 ,是在范围(1,n)内产生具有最低内存消耗的数据结构的算法,其中n是常量。

    26 回复  |  直到 6 年前
        1
  •  68
  •   Ben S    15 年前

    有很多方法可以做到 primality test .

    实际上没有数据结构可供您查询。如果你有很多数字要测试,你应该运行一个 probabilistic test 因为它们更快,然后用 deterministic test 以确保数字是质数。

    你应该知道,最快的算法背后的数学并不适合胆小的人。

        2
  •  188
  •   Mark Dickinson Alexandru    7 年前

    一般素数测试的最快算法是 AKS . 维基百科的文章对它进行了详细的描述,并链接到了原文。

    如果你想找到大的数字,可以研究具有特殊形式的素数,比如 Mersenne primes .

    我通常实现的算法(易于理解和编码)如下(在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
    

    这是经典的变种 O(sqrt(N)) 算法。它使用了这样一个事实:素数(2和3除外)的形式 6k - 1 6k + 1 只看这个形式的除数。

    有时,如果我真的想要速度和 范围有限 ,我实现了一个基于 Fermat's little theorem . 如果我真的想要更快的速度(即完全避免O(sqrt(n))算法),我会预先计算误报(请参见 Carmichael 然后进行二进制搜索。这是迄今为止我实现的最快的测试,唯一的缺点是范围有限。

        3
  •  24
  •   paxdiablo    15 年前

    在我看来,最好的方法是使用以前的方法。

    有第一个列表 N 在互联网上使用 n 至少伸展到 fifty million . 下载这些文件并使用它们,它可能比任何其他方法都快得多。

    如果你想要一个真正的算法来制作你自己的素数,维基百科有很多关于素数的好东西。 here ,包括指向各种方法的链接,以及基本测试 here 基于概率和快速确定性方法。

    我们应该齐心协力找到最初的十亿个(甚至更多)素数,并把它们发布到网上某个地方,这样人们就可以一次又一次地停止做同样的工作,而且……:-)

        4
  •  8
  •   saurabh kumar    8 年前
    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
    

    https://en.wikipedia.org/wiki/AKS_primality_test

        5
  •  6
  •   matt b    15 年前

    根据维基百科, the Sieve of Eratosthenes complexity O(n * (log n) * (log log n)) and requires O(n) memory -所以如果你不测试特别大的数字,这是一个很好的开始。

        6
  •  4
  •   Fouad Boukredine    6 年前

    在python 3中:

    def is_prime(a):
        if a < 2:
            return False
        elif a!=2 and a % 2 == 0:
            return False
        else:
            return all (a % i for i in range(3, int(a**0.5)+1))
    

    说明: 质数是一个只能被自身和1除尽的数。EX:2,3,5,7…

    1)如果a;lt;2: 如果“a”小于2,则不是质数。

    2)ELIF A!=2和a%2==0: 如果“a”可以被2除,那么它绝对不是素数。但是如果a=2,我们不想计算它,因为它是质数。因此,条件A!= 2

    3)返回所有(范围(3,int(a)中i的%i 0.5)+1):**首先看一下all()命令在python中的作用。 从3开始,我们将“a”除以它的平方根(a**0.5)。如果“a”可分割,则输出将为假。 为什么是平方根?假设a=16。16的平方根=4。我们到15点才需要评估。我们只需要查到4点就可以知道这不是一个素数。

    额外的: 查找一个范围内所有素数的循环。

    for i in range(1,100):
        if is_prime(i):
            print("{} is a prime number".format(i))
    
        7
  •  3
  •   LetzerWille    7 年前

    可以用sympy .

    import sympy
    
    sympy.ntheory.primetest.isprime(33393939393929292929292911111111)
    
    True
    

    来自sympy医生。第一步是寻找琐碎的因素,如果找到这些因素,可以快速返回。接下来,如果筛子足够大,则对筛子进行二分搜索。对于较小的数字,使用已知在其范围内没有反例的基来执行一组确定性米勒-拉宾测试。最后,如果数字大于2^64,则执行强BPSW测试。虽然这是一个可能的素数检验,我们相信反例存在,但没有已知的反例。

        8
  •  2
  •   Calmarius    7 年前

    参加聚会太晚了,但希望这能有所帮助。如果你正在寻找大素数,这是相关的:

    要测试大奇数,需要使用费马测试和/或米勒-拉宾测试。

    这些测试使用了非常昂贵的模块化求幂,因为 n 比特数求幂至少需要 N号 大整数乘法和 n 大整数除数。这意味着模幂运算的复杂性是O(n_3)。

    所以在使用大炮之前,你需要做一些试验性的划分。但不要天真地这么做,有一种方法可以很快做到。 首先,将尽可能多的素数相乘到一个你用来表示大整数的词中。如果使用32位字,将3*5*7*11*13*17*19*23*29=3234846615相乘,然后用欧几里得算法测试的数字计算最大公因数。在第一步之后,该数字将减小到字大小以下,并在不执行完整的大整数除法的情况下继续该算法。如果是GCD!=1,这意味着你们相乘的一个素数除以这个数,所以你们有一个证据证明它不是素数。然后继续31*37*41*43*47=95041567,依此类推。

    一旦你以这种方式测试了几百(或数千)个素数,你可以做40轮米勒拉宾测试来确认这个数字是素数,40轮之后你可以确定这个数字是素数,只有2^-80的机会不是(这更可能是你的硬件故障…)。

        9
  •  2
  •   Ralf    6 年前

    我比较了最流行的建议的效率,以确定一个数字是否是素数。我用过 python 3.6 ubuntu 17.10 ;我用高达100.000的数字进行测试(您可以使用下面的代码使用更大的数字进行测试)。

    第一个图比较了函数(在我的答案中会进一步解释),显示增加数字时,最后一个函数的增长速度不如第一个函数。

    plot1

    在第二个图中,我们可以看到,在素数的情况下,时间是稳定增长的,但非素数在时间上并没有那么快的增长(因为它们中的大多数可以在早期被消除)。

    plot2

    以下是我使用的功能:

    1. this answer this answer 建议使用 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 使用了某种while循环:

      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 包括一个版本 for 循环:

      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. 我把其他答案中的一些想法混合到一个新的答案中:

      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
      

    下面是我的脚本,用于比较变量:

    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
    

    运行函数 compare_functions(n=10**5) (数字高达100.000)我得到这个输出:

    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 |
     ---------------------------------------------------------------------
    

    然后,运行函数 compare_functions(n=10**6) (数字高达1.000.000)我得到这个输出:

    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 |
     ---------------------------------------------------------------------
    

    我使用以下脚本绘制结果:

    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()
    
        10
  •  1
  •   Oleksandr Shmyheliuk    8 年前

    Python 3:

    def is_prime(a):
        return a > 1 and all(a % i for i in range(2, int(a**0.5) + 1))
    
        11
  •  1
  •   WhyAreYouReadingThis Marley Plant    7 年前

    我有一个基本函数,它一直工作到(2^61)-1这里:

    from math import sqrt
    def isprime(num): num > 1 and return all(num % x for x in range(2, int(sqrt(num)+1)))
    

    说明:

    这个 all() 函数可以重新定义为:

    def all(variables):
        for element in variables:
            if not element: return False
        return True
    

    这个 全部() 函数只经过一系列bools/number并返回 False 如果看到0或 .

    这个 sqrt() 函数只是执行 平方根 一个数字。

    例如:

    >>> from math import sqrt
    >>> sqrt(9)
    >>> 3
    >>> sqrt(100)
    >>> 10
    

    这个 num % x 零件返回 余款 num/x。

    最后, range(2, int(sqrt(num))) 意味着它将创建一个 列表 从2点开始到 int(sqrt(num)+1)

    有关范围的更多信息,请查看此 website !

    这个 num > 1 部分只是检查变量 num 大于1,因为1和0不被视为质数。

    希望这有帮助:)

        12
  •  1
  •   Vlad Bezden    7 年前

    在蟒蛇中:

    def is_prime(n):
        return not any(n % p == 0 for p in range(2, int(math.sqrt(n)) + 1))
    

    从数学形式主义到Python的更直接的转换将使用 所有(n%p!= 0… 但这需要对P的所有值进行严格的评估。 没有任何 如果找到真值,版本可以提前终止。

        13
  •  1
  •   Mahdi Pourrostam    7 年前

    素数javascript的最佳算法

     function isPrime(num) {
          if (num <= 1) return false;
          else if (num <= 3) return true;
          else if (num % 2 == 0 || num % 3 == 0) return false;
          var i = 5;
          while (i * i <= num) {
            if (num % i == 0 || num % (i + 2) == 0) return false;
            i += 6;
          }
          return true
        }
    
        14
  •  1
  •   Piotr Dabkowski    6 年前

    对于大数字,您不能简单地检查候选数字n是否可以被小于sqrt(n)的任何数字整除。有更多可扩展的测试可用,例如 Miller-Rabin primality test . 下面是Python中的实现:

    def is_prime(x):
        """Fast implementation fo Miller-Rabin primality test, guaranteed to be correct."""
        import math
        def get_sd(x):
            """Returns (s: int, d: int) for which x = d*2^s """
            if not x: return 0, 0
            s = 0
            while 1:
                if x % 2 == 0:
                    x /= 2
                    s += 1
                else:
                    return s, x
        if x <= 2:
            return x == 2
        # x - 1 = d*2^s
        s, d = get_sd(x - 1)
        if not s:
            return False  # divisible by 2!
        log2x = int(math.log(x) / math.log(2)) + 1
        # As long as Riemann hypothesis holds true, it is impossible
        # that all the numbers below this threshold are strong liars.
        # Hence the number is guaranteed to be a prime if no contradiction is found.
        threshold = min(x, 2*log2x*log2x+1)
        for a in range(2, threshold):
            # From Fermat's little theorem if x is a prime then a^(x-1) % x == 1
            # Hence the below must hold true if x is indeed a prime:
            if pow(a, d, x) != 1:
                for r in range(0, s):
                    if -pow(a, d*2**r, x) % x == 1:
                        break
                else:
                    # Contradicts Fermat's little theorem, hence not a prime.
                    return False
        # No contradiction found, hence x must be a prime.
        return True
    

    你可以用它找到巨大的质数:

    x = 10000000000000000000000000000000000000000000000000000000000000000000000000000
    for e in range(1000):
        if is_prime(x + e):
            print('%d is a prime!' % (x + e))
            break
    
    # 10000000000000000000000000000000000000000000000000000000000000000000000000133 is a prime!
    

    如果要测试随机整数,可能需要先测试候选数是否可以被小于1000的素数整除,然后再调用Miller Rabin。这将帮助您过滤掉明显的非素数,如10444344345。

        15
  •  0
  •   Derri Leahy    8 年前

    类似于前面提到的AKS算法

    public static boolean isPrime(int n) {
    
        if(n == 2 || n == 3) return true;
        if((n & 1 ) == 0 || n % 3 == 0) return false;
        int limit = (int)Math.sqrt(n) + 1;
        for(int i = 5, w = 2; i <= limit; i += w, w = 6 - w) {
            if(n % i == 0) return false;
            numChecks++;
        }
        return true;
    }
    
        16
  •  0
  •   Harsh Singh    7 年前

    找出一个范围内的一个或多个数字是否是质数。

    #!usr/bin/python3
    
    def prime_check(*args):
        for arg in args:
            if arg > 1:     # prime numbers are greater than 1
                for i in range(2,arg):   # check for factors
                    if(arg % i) == 0:
                        print(arg,"is not Prime")
                        print(i,"times",arg//i,"is",arg)
                        break
                else:
                    print(arg,"is Prime")
    
                # if input number is less than
                # or equal to 1, it is not prime
            else:
                print(arg,"is not Prime")
        return
    
    # Calling Now
    prime_check(*list(range(101)))  # This will check all the numbers in range 0 to 100 
    prime_check(#anynumber)         # Put any number while calling it will check.
    
        17
  •  0
  •   DKB    7 年前
    myInp=int(input("Enter a number: "))
    if myInp==1:
        print("The number {} is neither a prime not composite no".format(myInp))
    elif myInp>1:
        for i in range(2,myInp//2+1):
            if myInp%i==0:
                print("The Number {} is not a prime no".format(myInp))
                print("Because",i,"times",myInp//i,"is",myInp)
                break
        else:
            print("The Number {} is a prime no".format(myInp))
    else:
        print("Alas the no {} is a not a prime no".format(myInp))
    
        18
  •  0
  •   Patrick Jane    7 年前

    你可以试试这个。

    def main():
        try:
            user_in = int(input("Enter a number to determine whether the number is prime or not: "))
        except ValueError:
            print()
            print("You must enter a number!")
            print()
            return
        list_range = list(range(2,user_in+1))
        divisor_list = []
        for number in list_range:
            if user_in%number==0:
                divisor_list.append(number)
        if len(divisor_list) < 2:
            print(user_in, "is a prime number!")
            return
        else:
            print(user_in, "is not a prime number!")
            return
    main()
    
        19
  •  0
  •   grepit    7 年前

    以前的大多数答案都是正确的,但这里还有一种方法可以检验一个数是素数。作为补充, 素数 是大于1的整数,其唯一因子是1及其本身。( source )

    解决方案:

    通常,您可以构建一个循环并开始测试您的数字,看看它是否可以被1、2、3…整除到您正在测试的数字…等等,但是为了减少检查时间,您可以将数字除以数字值的一半,因为一个数字不能被超过一半的值整除。 例如,如果你想看到100是一个质数,你可以循环到50。

    实际代码 :

    def find_prime(number):
        if(number ==1):
            return False
        # we are dividiing and rounding and then adding the remainder to increment !
        # to cover not fully divisible value to go up forexample 23 becomes 11
        stop=number//2+number%2
        #loop through up to the half of the values
        for item in range(2,stop):
            if number%item==0:
               return False
            print(number)
        return True
    
    
    if(find_prime(3)):
        print("it's a prime number !!")
    else:
        print("it's not a prime")  
    
        20
  •  0
  •   AlirezaAsadi    7 年前

    我们可以使用Java流在O(Sqt(n))中实现这一点;考虑到非EMATCH是一种短路方法,当发现不需要用于确定结果时,停止该操作:

    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    System.out.println(n == 2 ? "Prime" : IntStream.rangeClosed(2, ((int)(Math.sqrt(n)) + 1)).noneMatch(a -> n % a == 0) ? "Prime" : "Not Prime");
    
        21
  •  0
  •   Stefan Repcek    6 年前

    在Java-8流和lambda的帮助下,只需几行代码即可实现:

    public static boolean isPrime(int candidate){
            int candidateRoot = (int) Math.sqrt( (double) candidate);
            return IntStream.range(2,candidateRoot)
                    .boxed().noneMatch(x -> candidate % x == 0);
        }
    

    性能应接近 o(qRT(n)) . 也许有人觉得它有用。

        22
  •  0
  •   Richie Bendall    6 年前

    这是我的答案:

    def isprime(num):
        return num <= 3 or (num + 1) % 6 == 0 or (num - 1) % 6 == 0
    

    如果下面的任何属性为true,则函数将返回true。这些性质在数学上定义了素数是什么。

    1. 数字小于或等于3
    2. 数字+1可以被6整除
    3. 数字-1可以被6整除
        23
  •  -1
  •   jason    15 年前

    最小的记忆?这不是最小的,而是朝着正确的方向迈出的一步。

    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<int> 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];
        }
    }
    

    当然,您必须指定 CheckPrimality .

        24
  •  -1
  •   Spl1ce    8 年前

    我认为最快的方法之一就是我的方法。

    void prime(long long int number) {
        // Establishing Variables
        long long int i = 5;
        int w = 2;
        const long long int lim = sqrt(number);
    
        // Gets 2 and 3 out of the way
        if (number == 1) { cout << number << " is hard to classify. \n";  return; }
        if (number == 2) { cout << number << " is Prime. \n";  return; }
        if (number == 3) { cout << number << " is Prime. \n";  return; }
    
        // Tests Odd Ball Factors
        if (number % 2 == 0) { cout << number << " is not Prime. \n";  return; }
        if (number % 3 == 0) { cout << number << " is not Prime. \n";  return; }
    
        while (i <= lim) {
            if (number % i == 0) { cout << number << " is not Prime. \n";  return; }
            // Tests Number
            i = i + w; // Increments number
            w = 6 - i; // We already tested 2 and 3
            // So this removes testing multepules of this
        }
        cout << number << " is Prime. \n"; return;
    }
    
        25
  •  -1
  •   gaurav    7 年前
    public static boolean isPrime(int number) {
     if(number < 2)
       return false;
     else if(number == 2 || number == 3)
            return true;
          else {
            for(int i=2;i<=number/2;i++)
               if(number%i == 0)
                 return false;
               else if(i==number/2)
                    return true;
          }
        return false;
    }
    
        26
  •  -3
  •   Brad Larson    6 年前

    质数的第一个规则:如果除以2等于整数,则不等于质数。

    要知道使用任何计算机语言最快的方法是使用字符串而不是数学进行类型匹配。匹配字符串浮点数。

    • 除以2,,,n=n/2
    • 将此转换为字符串,,,n=string(n)
    • 如果是,则在n:{ printf“是的,我是最棒的!”
      }
    推荐文章