Chinaunix首页 | 论坛 | 博客

AAA

  • 博客访问: 18434
  • 博文数量: 33
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 330
  • 用 户 组: 普通用户
  • 注册时间: 2015-04-17 08:23
个人简介

好记性不如烂笔头,记录学习历程和随想云云,欢迎各位大虾拍砖

文章分类

全部博文(33)

文章存档

2015年(33)

我的朋友
最近访客

分类: C/C++

2015-05-04 22:01:42

【问题描述】

Description:

Count the number of prime numbers less than a non-negative number, n

【解决方案】

Wiki:

点击(此处)折叠或打开

  1. int countPrimes(int n)
  2. {
  3.     if(n < 0)
  4.     {
  5.         return -1;
  6.     }

  7.     int i,j;
  8.     int count = 0;
  9.     char *primes = (char *)malloc(sizeof(char) * n);

  10.     memset(primes, 0, sizeof(char) * n);

  11.     primes[0] = 1;
  12.     primes[1] = 1;

  13.     for(i = 2; i * i < n; i++)
  14.     {
  15.         if(!primes[i])
  16.         {
  17.             for(j = i; j * i < n; j++)
  18.             {
  19.                 primes[i * j] = 1;
  20.             }
  21.         }
  22.     }

  23.     for(i = 2; i < n; i++)
  24.     {
  25.         if(!primes[i])
  26.         {
  27.             count++;
  28.         }
  29.     }

  30.     free(primes);
  31.     primes = NULL;

  32.     return count;
  33. }


阅读(276) | 评论(0) | 转发(0) |
0

上一篇:Happy Number

下一篇:Valid Sudoku

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