素数,也就是质数.若一个数字,除了它自己和1,不能被任何其它整数整除,则本数字被称为'素数'. 一个最粗暴的baseline如下:

#include <stdio.h>
#include <string.h>

bool is_prime_number(int val)
{
    int num = 0;
    int t;
    for(int i=1; i*i<=val; i++)
    {
        t = val / i;
        if( t * i == val ) num++;
        if(num>1) return false;
    }
    return true;
}

int get_int(const char *str)
{
    int sum = 0;
    int len = strlen(str);
    for(int i=0; i<len; i++)
    {
        if(*(str+i) >= '0' && *(str+i) <= '9' )
            sum = sum * 10 + *(str+i) - '0';
    }
    return sum;
}

int main(int argc,char *argv[])
{
    int max = 0;
    int size = 0 ;
    if(argc>1) max = get_int(argv[1]);
    if(!max) max = 100;
    for(int i=2; i<max; i++)
    {
        if(is_prime_number(i))
        {
            printf("%d\n",i);
            size ++ ;
        }
    }
    printf("size:%d\n",size);
    return 0;
}

Output

[yu@argcandargv-com prime_number]$ g++ prime_number_list.cc -o prime_number_list
[yu@argcandargv-com prime_number]$ ./prime_number_list
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
size:25

Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

2 Comments

vfhky · April 14, 2014 at 15:09

Google Chrome 30.0.1599.101 Google Chrome 30.0.1599.101 Windows 7 x64 Edition Windows 7 x64 Edition

代码很严谨,喜欢这种风格。

    yu · April 14, 2014 at 17:51

    Google Chrome 33.0.1750.152 Google Chrome 33.0.1750.152 GNU/Linux x64 GNU/Linux x64

    @vfhky 囧,好久前的东西了,现在看了满是嘈点

Leave a Reply

Your email address will not be published. Required fields are marked *