prime numbers(素数)

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值