snippet from SICP 1.2.6
One way to test if a number is prime is to find the number's divisors. The following program finds the smallest integral divisor (greater than 1) of a given number n. It does this in a straightforward way, by testing n for divisibility by successive integers starting with 2.
We can test whether a number is prime as follows: n is prime if and only if n is its own smallest divisor.
The end test for find-divisor is based on the fact that if √n is not prime it must have a divisor less than or equal to n This means that the algorithm need only test divisors between 1 and √n. Consequently, the number of steps required to identify n as prime will have order of growth Θ(√n).
The code as below is compiled in VC++ 2005, Ricky 2009-6-28
---------------------------------------------------------------------------------------------------------
// primenum.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <math.h>
#define TRUE 1
#define FALSE 0
/*----------------------------------------------------
function: find_divisor
description:find divisor of a given number
input: n: the given number
test_divisor: the starting num
output:the divisor
remark:
此算法基于以下事实:如果n不是素数,它必然有一个小于或者等于√n的因子。
这也意味着该算法只需在1和√n之间检查因子。由此可知,确定是否素数所需的步数将具有θ(√n)的增长阶。
------------------------------------------------------*/
int find_divisor(int n, int test_divisor)
{
if( test_divisor*test_divisor > n )
{
return n;
}
else if ( 0 == n%test_divisor )
{
return test_divisor;
}
else
{
return find_divisor(n, test_divisor+1);
}
}
/*------------------------------------------------------
function: smallest_divisor
description: get the smallest divisor of a given num
input: n: the given num
output: the smallest divisor
remark: by testing n for divisibility by successive integers starting with 2.
------------------------------------------------------*/
int smallest_divisor(int n)
{
return find_divisor(n, 2);
}
/*------------------------------------------------------
function: is_prime
description: check a given num whether is prime
input: n: the given num
output: true/false
remark: We can test whether a number is prime as follows: n is prime if and only if n is its own smallest divisor
------------------------------------------------------*/
bool is_prime(int n)
{
return (smallest_divisor(n) == n) ? TRUE: FALSE;
}
int _tmain(int argc, _TCHAR* argv[])
{
bool b = is_prime(17);
b = is_prime(88);
return 0;
}