LoginSignup
0
0

More than 1 year has passed since last update.

【PHP】【素数判定】PHPで素数問題を解く

Last updated at Posted at 2022-06-06

素数とは

1・2以上の数※0と1は素数ではない
2・1とその数だけでしか割りきれない数

コード1

<?php
 
$num = intval(fgets(STDIN));
$point = 0;
if ($num === 0) goto output;
foreach (range(1,$num) as $j) {    
    if ($num % $j === 0) $point++;    
}
output:
echo $num,":",$point === 2 ? "素数だよ。":"素数じゃない。";

結果1

3:素数だよ。

コード2

<?php
foreach (range(0,100) as $i) {
    $point = 0;
    foreach (range(1,$i) as $j) {   
        if ($i === 0) break;
        if ($i % $j === 0) $point++;    
    }
    if ($point === 2) {
        echo $i,PHP_EOL;
    }
}

結果2

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
0
0
15

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0