from ACL1 ACL1B B - Sum is Multiple
m = max([p ** f[p] for p in f]).k = -1 * inv_mod(m, r) * m is fine, sodef solve(N):
from math import gcd
if N == 1:
return 1
ret = N - 1
for n in all_divisor(2 * N, includeN=False):
m = (2 * N) // n
if gcd(m, n) != 1:
continue
k = crt(0, n, -1, m)
if k < ret:
ret = k
return ret
def solve(N):
if N == 1:
return 1
factors = factor(2 * N)
num_factors = len(factors)
if num_factors == 1:
return N - 1
factors = [p ** factors[p] for p in factors]
ret = N - 1
for i in range(2 ** num_factors - 1):
prod = 1
j = 0
while i:
if i & 1:
prod *= factors[j]
j += 1
i >>= 1
rest = (2 * N) // prod
k = (-pow(prod, -1, rest) * prod) % (2 * N)
if k < ret:
ret = k
return ret
- Ummm [AC 21 TLE 21](https://atcoder.jp/contests/acl1/submissions/17258486)
- Is the prime factorization slow or the re-bundling part slow?
- I replaced it with [Prime factorize by O(n^(1/4))](/en/Prime%20factorize%20by%20O(n%5E(1%2F4))) and it came through [51msec](https://atcoder.jp/contests/acl1/submissions/17259156)
- Also, pow asking for [Inverse Element in mod P](/en/Inverse%20Element%20in%20mod%20P) is a rather new feature since Python 3.8, so it didn't work in PyPy.
- `ValueError: pow() 2nd argument cannot be negative when 3rd argument specified`
This page is auto-translated from /nishio/ACL1B using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I'm very happy to spread my thought to non-Japanese readers.