素数缓冲求法,可重用类

<script language="JavaScript" type="text/javascript"> </script>   #include <iostream>
  #include <algorithm>
  #include <vector>
  #include <iterator>
  
  template <typename T>
  class PrimerCache
- {
      typedef T   ValueType;
      typedef std::vector<ValueType> IntArray;
      typedef typename IntArray::const_iterator IntPtr;
  
      static IntArray mCache;
       
  protected:
      bool Test(ValueType num) const
-     {
          // make sure : half  < mCache.back()
          // !!! IncreaseCache(half) promised this !!!        
  
          ValueType half = num / 2 + 1;
         
          for(IntPtr i = mCache.begin(); *i < half && i != mCache.end();  ++i)
-         {
              if( num % (*i) == 0)
-             {
                   return false;
              }
          }         
          return true;
      }
  
      void IncreaseCache(ValueType num) const
-     {
          ValueType upper = mCache.back();
           
          while (upper < num)
-         {
              upper++;             
              if( Test(upper))
-             {
                  mCache.push_back(upper);
              }
               
          }         
      }
  
      bool InCache(ValueType num) const
-     {
          return std::binary_search(mCache.begin(), mCache.end(), num);
      }
  public:
      PrimerCache(ValueType lowerNum = 1000)
-     {
          IsPrimer(lowerNum);
      }
  
      bool IsPrimer(ValueType num) const
-     {
          ValueType biggestPrimer = mCache.back() + 1;
  
          if( biggestPrimer > num)
-         {
              return InCache(num);
          }
          else
-         {
              IncreaseCache(num);
              return Test(num);  
          }
      }
      friend std::ostream& operator<<(std::ostream& out, PrimerCache const& primerCache)
-     {
          IntArray& cache = primerCache.mCache;
          out << "Primer Cache Has " << cache.size() << " elements, they are " << std::endl;  
          std::copy(cache.begin(), cache.end(), std::ostream_iterator<int>(out, ","));
          return out;
      }
  };
  //the one and only cache;
  template <typename T>
  typename PrimerCache<T>::IntArray PrimerCache<T>::mCache = IntArray(1, 2);
  
  template <typename CacheType>
  void TestPrimer(CacheType& cache, int num)
- {
      int test = num;
      std::cout<< test << " is primer? "<< std::boolalpha << cache.IsPrimer(test) << std::endl;
  }
  
  
  int main()
- {
      PrimerCache<int> primer;
      int test;
  
      TestPrimer(primer, 1);
      TestPrimer(primer, 2);
      TestPrimer(primer, 4);
      TestPrimer(primer, 5);
      TestPrimer(primer, 99);
      TestPrimer(primer, 97);
      TestPrimer(primer, 101);
      TestPrimer(primer, 102);
      TestPrimer(primer, 98);
      TestPrimer(primer, 96);
       
  
      std::cout << primer << std::endl;
  
      std::cout << "primer is " << sizeof ( PrimerCache<int>) << std::endl;
  
      PrimerCache<short> p(10);
      
      TestPrimer(p, 1);
      TestPrimer(p, 2);
  
      std::cout << p << std::endl;
      return 0;
  }
  
在Python中,可以使用以下几种方来求解质数: 1. 基本方:遍历从2到n-1的所有数字,判断是否能整除n。如果存在能整除n的数字,则n不是质数;否则,n是质数。 ```python def is_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True ``` 2. 优化方:在基本方的基础上,可以进行一些优化。例如,只需要遍历从2到sqrt(n)的数字即可,因为如果存在大于sqrt(n)的因子,那么一定存在小于sqrt(n)的因子。 ```python import math def is_prime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True ``` 3. Sieve of Eratosthenes(埃拉托斯特尼筛):该方通过不断筛选出质数的倍数来找到所有质数。具体步骤如下: - 创建一个长度为n+1的布尔数组is_prime,并将所有元素初始化为True。 - 将is_prime和is_prime设置为False,因为0和1不是质数。 - 从2开始遍历到sqrt(n),对于每个素数p,将is_prime[p]设置为True,并将p的倍数is_prime[p*i](i从2开始)设置为False。 - 遍历is_prime数组,将为True的索引值添加到结果列表中。 ```python def sieve_of_eratosthenes(n): is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False p = 2 while p * p <= n: if is_prime[p]: for i in range(p * p, n + 1, p): is_prime[i] = False p += 1 primes = [i for i in range(n + 1) if is_prime[i]] return primes ``` 这些是Python中常用的几种质数求解方。你可以根据具体需求选择合适的方来使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值