找出一定范围内的素数(质数)

判断一个数是不是质数

1
2
3
4
5
6
7
8
9
10
11
function isprime($n){
    if($n < 2){
        return false;
    }
    for ($i=2; $i*$i <= $n; $i++) {
        if($n % $i == 0){
            return false;
        }
    }
    return true;
}

使用上面的函数或者直接在下面的函数中判断,找寻一定范围内的质数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function sieve($n){
    $array = array();
 
    for ($i=0; $i <= $n; $i++) {
        if($i % 2 != 0){
            if($i > 2){
                // if(isprime($i)){
                //  $array[] = $i;
                // }
 
                $isprime = true;
                for ($j=2; $j <= ceil(sqrt($i)); $j++) {
                    if($j % 2 != 0){
                        if($i % $j == 0){
                            $isprime = false;
                            break;
                        }
                    }
                }
                if($isprime){
                    $array[] = $i;
                }
            }
        }
    }
 
    return $array;
}

  

print_r(sieve(100));

Array
(
    [0] => 3
    [1] => 5
    [2] => 7
    [3] => 11
    [4] => 13
    [5] => 17
    [6] => 19
    [7] => 23
    [8] => 29
    [9] => 31
    [10] => 37
    [11] => 41
    [12] => 43
    [13] => 47
    [14] => 53
    [15] => 59
    [16] => 61
    [17] => 67
    [18] => 71
    [19] => 73
    [20] => 79
    [21] => 83
    [22] => 89
    [23] => 97
)
posted @   sundong_wyz  阅读(1609)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示