結果

問題 No.3030 ミラー・ラビン素数判定法のテスト
ユーザー 一野瀬翔吾一野瀬翔吾
提出日時 2024-04-30 22:42:41
言語 Go
(1.22.1)
結果
AC  
実行時間 395 ms / 9,973 ms
コード長 990 bytes
コンパイル時間 11,451 ms
コンパイル使用メモリ 236,520 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-30 22:42:55
合計ジャッジ時間 14,338 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,816 KB
testcase_01 AC 1 ms
6,816 KB
testcase_02 AC 1 ms
6,940 KB
testcase_03 AC 2 ms
6,940 KB
testcase_04 AC 300 ms
6,944 KB
testcase_05 AC 306 ms
6,944 KB
testcase_06 AC 257 ms
6,940 KB
testcase_07 AC 244 ms
6,944 KB
testcase_08 AC 245 ms
6,944 KB
testcase_09 AC 395 ms
6,940 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"fmt"
	"math/bits"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		var x uint64
		fmt.Scanf("%d", &x)
		if isPrime(x) {
			fmt.Printf("%d 1\n", x)
		} else {
			fmt.Printf("%d 0\n", x)
		}
	}
}

func modMul(a, b, m uint64) uint64 {
	h, l := bits.Mul64(a, b)
	_, rem := bits.Div64(h, l, m)
	return rem
}

func modPow(x, y, m uint64) uint64 {
	res := uint64(1)
	for y > 0 {
		if y&1 != 0 {
			res = modMul(res, x, m)
		}
		x = modMul(x, x, m)
		y >>= 1
	}
	return res
}

func isPrime(x uint64) bool {
	if x <= 1 {
		return false
	}
	if x == 2 {
		return true
	}
	if x%2 == 0 {
		return false
	}

	s := bits.TrailingZeros64(x - 1)
	d := (x - 1) >> s

	for _, a := range []uint64{2, 325, 9375, 28178, 450775, 9780504, 1795265022} {
		if a%x == 0 {
			continue
		}
		t := modPow(a, d, x)
		if t == 1 || t == x-1 {
			continue
		}
		for i := 1; t != x-1; i++ {
			if i >= s {
				return false
			}
			t = modMul(t, t, x)
		}
	}
	return true
}
0