Last active
October 20, 2017 02:07
-
-
Save gtongy/4016599d53b49a1684bda598120f4d16 to your computer and use it in GitHub Desktop.
bool配列を用いた素数判定プログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
素数判定プログラム | |
アルゴリズムとしてエラストテネスの篩を使い、 | |
素数かどうか判定するのにbool配列を使用する | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math" | |
"time" | |
) | |
const ( | |
N = 1000001 | |
) | |
func main() { | |
start := time.Now() | |
// 探索リスト | |
search := make([]bool, N) | |
for key, _ := range search { | |
search[key] = true | |
} | |
array_size := int(math.Floor(math.Sqrt(N))) | |
for i := 2; i < array_size; i++ { | |
// 素数の倍数のものはfalseを代入 | |
for j := 2; i*j < N; j++ { | |
search[i*j] = false | |
} | |
} | |
var primes []int | |
for k := 2; k < N; k++ { | |
// 探索リストがtrueのものは配列に追加 | |
if search[k] == true { | |
primes = append(primes, k) | |
} | |
} | |
fmt.Printf("合計: %d\n", sum(primes)) | |
fmt.Printf("最大: %d\n", primes[len(primes)-1]) | |
end := time.Now() | |
fmt.Printf("%f秒\n", (end.Sub(start)).Seconds()) | |
} | |
// スライス内の合計値の計算 | |
func sum(arr []int) int { | |
val := 0 | |
for i := 0; i < len(arr); i++ { | |
val += arr[i] | |
} | |
return val | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('N', 1000001); | |
$time_start = microtime(true); | |
// 探索リスト | |
$search_list = array_fill(1, N, true); | |
for ($i = 2; $i <= sqrt(N); $i++) { | |
// 素数ではない場合、falseを代入 | |
for ($j = 2; $i*$j <= N; $j++) { | |
$search_list[$i * $j] = false; | |
} | |
} | |
$primes = []; | |
// 探索リストのうち、素数の場合のみ配列に代入 | |
for ($k = 2; $k <= N; $k++) { | |
if ($search_list[$k] === true) { | |
$primes[] = $k; | |
} | |
} | |
echo "合計: " . array_sum($primes),PHP_EOL; | |
echo "最大: " . $primes[count($primes)-1],PHP_EOL; | |
$time = microtime(true) - $time_start; | |
echo "実行時間: {$time} 秒",PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment