Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2495386
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-04-22 18:29:48

在算法课程中,我们接触的第一个算法,也是相对简单的算法就是穷举法。其实穷举法的思想是,我们在解决问题时,先确定问题域,通过测试每一个情况,直到我们找到我们想要的答案。
如求解1到100之间的素数,我们通过穷举法,一个数,一个数的判断该数是否是素数,代码如下:
  1. #include <stdio.h>

  2. /*判断n是否是素数,是返回1;不是返回0*/
  3. int isPrime(int n)
  4. {
  5.   int i;
  6.   for(i=2;i<n;i++)
  7.   {
  8.     if(n%== 0)
  9.     {
  10.       return 0;
  11.     }
  12.   }
  13.   return 1;
  14. }

  15. getPrime(int low, int high)
  16. {
  17.   int i;
  18.   for (i=low;i<=high;i++)
  19.   {
  20.     if(isPrime(i))
  21.     {
  22.       printf("%d ",i);
  23.     }
  24.   }
  25.   printf("\n");
  26. }

  27. int main(int argc,char* argv[])
  28. {
  29.   int low,high;
  30.   printf("please input the domain for searching prime\n");
  31.   printf("low limitation:");
  32.   scanf("%d",&low);
  33.   printf("high limitation:");
  34.   scanf("%d",&high);
  35.   printf("The whole primes in this domain are\n");
  36.   getPrime(low,high);
  37.   return 0;
  38. }
执行结果:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./3.3
please input the domain for searching prime
low limitation:1
high limitation:100
The whole primes in this domain are
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

又如:TOM一共有5本新书,要借给A,B,C三个人,每个人只能借1本,则TOM可以有多少种不同的借书方法。
我们可以通过穷举,所有的借书情况,然后找出我们需要的(每个人只能借一本),因此这种方法,也是通过穷举法实现的,代码如下:
  1. #include <stdio.h>

  2. /*计算TOM可以有多少种不同的借书方法*/
  3. int main(int argc, char* argv[])
  4. {
  5.   int i,j,k;
  6.   printf("There are different methods for TOM to distribute his book to A,B,C\n");
  7.   for(i=1;i<=5;i++)
  8.     for(j=1;j<=5;j++)
  9.       for(k=1;k<=5;k++)
  10.      if(!= j && j != k && k != i)
  11.      {
  12.      printf("(%d,%d,%d) ",i,j,k);
  13.          }
  14.   printf("\n");
  15.   return 0;
  16. }
执行结果如下:
There are different methods for TOM to distribute his book to A,B,C
(1,2,3) (1,2,4) (1,2,5) (1,3,2) (1,3,4) (1,3,5) (1,4,2) (1,4,3) (1,4,5) (1,5,2) (1,5,3) (1,5,4) (2,1,3) (2,1,4) (2,1,5) (2,3,1) (2,3,4) (2,3,5) (2,4,1) (2,4,3) (2,4,5) (2,5,1) (2,5,3) (2,5,4) (3,1,2) (3,1,4) (3,1,5) (3,2,1) (3,2,4) (3,2,5) (3,4,1) (3,4,2) (3,4,5) (3,5,1) (3,5,2) (3,5,4) (4,1,2) (4,1,3) (4,1,5) (4,2,1) (4,2,3) (4,2,5) (4,3,1) (4,3,2) (4,3,5) (4,5,1) (4,5,2) (4,5,3) (5,1,2) (5,1,3) (5,1,4) (5,2,1) (5,2,3) (5,2,4) (5,3,1) (5,3,2) (5,3,4) (5,4,1) (5,4,2) (5,4,3) 
阅读(2816) | 评论(0) | 转发(0) |
0

上一篇:谁在说谎

下一篇:递归与分治思想

给主人留下些什么吧!~~