結果
| 問題 | No.3478 XOR-Folding Primes |
| コンテスト | |
| ユーザー |
tomerun
|
| 提出日時 | 2026-03-20 22:34:07 |
| 言語 | Crystal (1.19.1) |
| 結果 |
AC
|
| 実行時間 | 1,323 ms / 4,000 ms |
| コード長 | 2,797 bytes |
| 記録 | |
| コンパイル時間 | 10,103 ms |
| コンパイル使用メモリ | 342,088 KB |
| 実行使用メモリ | 23,132 KB |
| 最終ジャッジ日時 | 2026-03-20 22:34:28 |
| 合計ジャッジ時間 | 15,597 ms |
|
ジャッジサーバーID (参考情報) |
judge2_0 / judge1_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 8 |
ソースコード
MOD = 998244353i64
IS_PRIME = Array.new(10_001_001, true)
2.upto(IS_PRIME.size - 1) do |i|
if IS_PRIME[i]
(i * 2).step(to: IS_PRIME.size - 1, by: i) do |j|
IS_PRIME[j] = false
end
end
end
PRIMES = (2...IS_PRIME.size).select { |i| IS_PRIME[i] }
TWINS = [] of Int32
7.step(to: IS_PRIME.size - 1, by: 4) do |i|
if IS_PRIME[i] && IS_PRIME[i - 2]
TWINS << i
end
end
read_line.to_i.times do
puts solve()
end
def solve
n, m = read_line.split.map(&.to_i)
if n == 1
return PRIMES.bsearch_index { |v, _| v > m }.not_nil!
end
mat = Matrix(Int64).new(3, 3)
cnt = TWINS.bsearch_index { |v, _| v > m } || TWINS.size
mat.a[1][0] = cnt
mat.a[2][0] = cnt
mat.a[0][1] = 1
mat.a[0][2] = 1
mat.a[1][2] = 1
mat.a[2][1] = 1
mat = mat.pow(n - 1)
ans = 0i64
v = [1, cnt, cnt]
3.times do |i|
3.times do |j|
ans += mat.a[i][j] * v[j]
end
end
ans % MOD
end
class Matrix(T)
@a : Array(Array(T))
getter :a, :d1, :d2
def initialize(n : Int32, m : Int32)
@a = Array.new(n) { Array.new(m, T.zero) }
@d1 = n
@d2 = m
end
def clone
ret = Matrix(T).new(@d1, @d2)
@d1.times do |i|
@d2.times do |j|
ret.a[i][j] = @a[i][j]
end
end
return ret
end
def [](idx : Int32)
return @a[idx]
end
def mul(other : Matrix(T))
if @d2 != other.d1
raise ArgumentError.new
end
d3 = other.d2
tmp = Array.new(d3) { Array.new(@d2, T.zero) }
d3.times do |i|
tr1 = tmp[i]
@d2.times do |j|
tr1[j] = other[j][i]
end
end
ret = Array.new(@d1) { Array.new(d3, T.zero) }
@d1.times do |i|
row1 = @a[i]
ret1 = ret[i]
d3.times do |j|
sum = T.zero
row2 = tmp[j]
@d2.times do |k|
sum += row1[k] * row2[k]
sum %= MOD
end
ret1[j] = sum
end
end
@a = ret
end
def mul_l(other : Matrix(T))
# in-place
if other.d2 != @d1
raise ArgumentError.new
end
d3 = @d2
tmp = Array.new(d3) { Array.new(@d1, T.zero) }
d3.times do |i|
tr1 = tmp[i]
@d1.times do |j|
tr1[j] = @a[j][i]
end
end
other.d1.times do |i|
row1 = other.a[i]
ret1 = @a[i]
d3.times do |j|
sum = T.zero
row2 = tmp[j]
other.d2.times do |k|
sum += row1[k] * row2[k]
sum %= MOD
end
ret1[j] = sum
end
end
end
def pow(p : Int64)
b = Matrix(T).new(@d1, @d2)
ret = Matrix(T).new(@d1, @d2)
@d1.times do |i|
@d2.times do |j|
b.a[i][j] = @a[i][j] % MOD
end
ret.a[i][i] = 1
end
while p > 0
if (p & 1) != 0
ret.mul_l(b)
end
b.mul(b)
p >>= 1
end
return ret
end
end
tomerun