isprime.h

来自「The source code samples for chapter 2, 4」· C头文件 代码 · 共 36 行

H
36
字号

#include <math.h>

inline
bool IsPrime(long n)
{
  // Special case: < 2
  if( n < 2 ) return false;

  // Special case: first couple of primes
  if( n == 2 || n == 3 )
  {
    return true;
  }

  // Special case: even
  if( n % 2 == 0 ) return false;

  // Special case: has a square root
  double  root = sqrt(double(n));
  if( double(long(root)) == root ) return false;

  const long begin = 3;
  const long end = long(root) + 1;

  // Special case: root < begin
  if( end < begin ) return true;

  for( long i = begin; i != end; ++i )
  {
    if( n % i == 0 ) return false;
  }

  return true;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?