PHPで素数の和を求めるプログラムを作ってみました。
$max = 100;
for ($i = 1; $i <= $max; $i++) {
for ($j = 1,$count = 0; $j <= $i; $j++) {
if ($i % $j === 0) {
$count += 1;
}
}
if ($count === 2) {
$primeNumbers[] = $i;
}
}
$total = 0;
foreach ($primeNumbers as $value) {
$total += $value;
}
print_r($primeNumbers);
echo $max, 'までの素数の合計:', $total;
Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 7
[4] => 11
[5] => 13
[6] => 17
[7] => 19
[8] => 23
[9] => 29
[10] => 31
[11] => 37
[12] => 41
[13] => 43
[14] => 47
[15] => 53
[16] => 59
[17] => 61
[18] => 67
[19] => 71
[20] => 73
[21] => 79
[22] => 83
[23] => 89
[24] => 97
)
100までの素数の合計:1060
没案(見苦しい)
$max = 100;
$primeNumbers = array(2);
for ($i = 2; $i <= $max; $i++) {
for($j = 2; $j < $i; $j++) {
if($i % $j === 0) {
break;
}
if($i === $j + 1){
$primeNumbers[] = $i;
}
}
}
$total = 0;
foreach ($primeNumbers as $value) {
$total += $value;
}
print_r($primeNumbers);
echo $max, 'までの素数の合計:', $total;
Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 7
[4] => 11
[5] => 13
[6] => 17
[7] => 19
[8] => 23
[9] => 29
[10] => 31
[11] => 37
[12] => 41
[13] => 43
[14] => 47
[15] => 53
[16] => 59
[17] => 61
[18] => 67
[19] => 71
[20] => 73
[21] => 79
[22] => 83
[23] => 89
[24] => 97
)
100までの素数の合計:1060