You can use several words in query to find by all of them at the same time. In addition, if you are lucky search understands word forms and some synonyms. It supports search by title and author. Examples:

  • 305 — search for 305, most probably it will find blogs about the Round 305
  • andrew stankevich contests — search for words "andrew", "stankevich" and "contests" at the same time
  • user:mikemirzayanov title:testlib — search containing "testlib" in title by MikeMirzayanov
  • "vk cup" — use quotes to find phrase as is
  • title:educational — search in title

Results

1.

modulo

Last visit:  8 years ago
Registered:  10 years ago
2.
By TLE, history, 8 years ago, In English
Linear Recurrence and Berlekamp-Massey Algorithm **#IjustWantContribution** It seems there isn't any blog about Berlekamp-Massey Algorithm around here, so I decided to go on a try. :P Acknowledgement: Hats off to matthew99 for introducing this algorithm. #### What is 'linear recurrence'? Assuming there is a (probably infinity) sequence $a_0,a_1...a_{n-1}$, we call this sequence satisfies a linear recurrence relation $p_1,p_2...p_m$, iff $\forall i \geq m,~a_i=\sum_{j=1}^m a_{i-j}p_j$. (Obviously, if $m\geq n$ any $p$ can do :P) #### How to calculate k-th term of a linear recurrence? For a polynomial $f(x)=\sum_{i=0}^{t} c_ix^i$, we define $G(f)=\sum_{i=0}^{t} c_ia_i$. Obviously $G$ satisfies $G(f)\pm G(g) =G(f \pm g)$. Because $a_i=\sum_{j=1}^m a_{i-j}p_j$, if we let $f(x)=x^m-\sum_{j=1}^m x^{m-j}p_j$, then $G(f)=0$. Also $G(fx),G(fx^2)...=0$. So $G(fg)=0$ (g is any polynomial). What we want is $G(x^k)$. Because $G(f\lfloor x^k/f\rfloor)=0$, then $G(x^k)=G(x^k \bmod f)$. [cut] We can calculate $x^k \b...
every $x \in [1,m]$, $y \in [0,n)$, you need to find the way modulo $998244353$. To reduce output, ,n)$, you need to find the way modulo $998244353$. To reduce output size, only output the bitwise-xor

Full text and comments »

  • Vote: I like it
  • +1492
  • Vote: I do not like it

3.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] Collection of little techniques #### Introduction There are a number of "small" algorithms and facts that come up again and again in problems. I feel like there I have had to explain them many times, partly because there are no blogs about them. On the other hand, writing a blog about them is also weird because there is not that much to be said. To settle these things "once and for all", I decided to write my own list about about common "small tricks" that don't really warrant a full tutorial because they can be adequately explained in a paragraph or two and there often isn't really anything to add except for padding. This blog is partly inspired by [user:adamant,2022-03-15]'s [blog](48417) from a few years ago. At first, I wanted to mimic adamant's blog structure exactly, but I found myself wanting to write longer paragraphs and using just bolded sentences as section headers got messy. Still, each section is short enough that it would not make much sense to write separate blogs about each of these things. A...
can be done by precomputing all quadratic residues modulo $p$., residues modulo $p$ are a random subset of $1, \ldots, p-1$, where a number is a quadratic residue with, will take it modulo a large prime. This introduces the possibility of a false negative, but if we pick, A quadratic residue modulo $p$ is any number $a$ that can be represented as a squaremodulo $p

Full text and comments »

  • Vote: I like it
  • +804
  • Vote: I do not like it

4.
By adamant, history, 19 months ago, In English
Complex FFT is not as bad as you think ... Probably. Hi everyone! As some of you _might_ already know, I don't like NTT. Primary reasons for this are: - I don't like modular arithmetic optimizations (Montgomery, etc). - I don't like NTT mods, and prefer good, old $10^9+7$. - I do like algebra of complex numbers. But, to my regret, the overwhelming mainstream in modern competitive programming is NTT. Primary reasons are: - It's allegedly faster. - It needs less memory. - It has no precision issues. - People don't like algebra of complex numbers. There is nothing I can do about the last, but today I'll address the first 3. Optimizing complex FFT was on my mind for quite some time, but I didn't really work on it _that much_ until the [blog](https://codeforces.me/blog/entry/142063) by [user:Qwerty1232,2025-04-24] on optimizing NTT has dropped, which motivated me to actually put some serious effort into this. In this blog, we will primarily focus on optimizations that are specific to complex arithmetic...
[Convolution](https://judge.yosupo.jp/problem/convolution_mod) modulo $998\;244\;353$, complex based FFT ends, consecutive complex numbers at once is the computation of component-wise productsmodulo $x^{n/2^k, is, find $C(x)$ modulo $x^n-i$? Well, we can notice that, multiplication when I really need to compute products modulo $M$ (for example when doing $A(kx) B(kx, on the $k$-th layer we have remainders of $A(x)$ and $B(x)$ modulo $x^{n/2^k} - \sqrt[2^k]{i, polynomial modulo $x^n-c$. Then, we can easily find the remainders of the polynomialmodulo $x^\frac, resulting array might have values up to $n C^2$, so if we want to find a convolutionmodulo $M = 10^9, their negacyclic convolution (i.e. the product modulo $x^n+1$) by computing just a single imaginary, we will have the sequence of remainders modulo $x^{n/2^k}-\sqrt[2^k]{i}$ , where $\sqrt[2^k]{i}$ is, , especially when dealing in convolutions modulo $M$?, -algo/math/cvector.hpp); - Take convolution modulo M [here](https://lib.cp-algorithms.com/cp-algo/math, /problem/convolution_mod) modulo $998\;244\;353$, complex based FFT ends up being in top-8 (if we, 1. Find its remainder modulo $x^n+1$ via imaginary cyclic convolution of length $\frac{n}{2}$; 2, As the powers $1, k, k^2, \dots$, when taken modulo $M$, would typically behave in an unpredictable, Naturally, same stands for reducing numbers modulo $M$, which would typically be done using Barrett, Now, what about convolutions modulo $M$? As we want $|z'-z| \leq \frac{1}{2}$ for correct rounding, So far so good! Except, $A(kx) B(kx)$ no longer commutes with finding convolutionmodulo $x^n+1, This allows us to generalize the approach. Let $P(x)$ and $Q(x)$ be the remaindersmodulo $x^n \pm, This way, all in all we will do a sequence of convolutions modulo $x^{\frac{n}{2}}-i$, then $x, When we do the imaginary-cyclic convolution, we effectively compute $C(x)$ modulo $x^n-i$. But at, is the remainder of $C(x)$ modulo $x^{2n}-k^{2n}$. This way, we can utilize our memory reduction, meaning that for a convolution modulo $M$ we need to satisfy

Full text and comments »

  • Vote: I like it
  • +731
  • Vote: I do not like it

5.
By parveen1981, history, 6 years ago, In English
I compiled a list of almost all useful blogs ever published on Codeforces [update: till 09.06.2021] <h3 style="color:red">If there are any blogs that I have missed, please tell in the comment section. Thank you.</h3> # Mathematics Stuff - [Number Theory in Competitive Programming [Tutorial]](https://codeforces.me/blog/entry/46620) - [Number of points on Convex hull with lattice points](https://codeforces.me/blog/entry/62183) - [FFT, big modulos, precision errors.](https://codeforces.me/blog/entry/48465) - [Number of ways between two vertices](https://codeforces.me/blog/entry/19078) - [Mathematics For Competitive Programming](https://codeforces.me/blog/entry/76938) - [FFT and NTT](https://codeforces.me/blog/entry/19862) - [Burnside Lemma](https://codeforces.me/blog/entry/51272) - [Number of positive integral solutions of equation 1/x+1/y=1/n!](https://codeforces.me/blog/entry/76836) - [On burnside (again)](https://codeforces.me/blog/entry/64860) - [Simple but often unknown theorems/lemmas/formula? Do you know?](https://codeforces.me/blog/entry/55912) - [Probabili...
from its remainder modulo huge integer](https://codeforces.me/blog/entry/73629) - [Short modular

Full text and comments »

  • Vote: I like it
  • +1500
  • Vote: I do not like it

6.
By neal, 8 years ago, In English
Blowing up unordered_map, and how to stop getting hacked on it C++ has always had the convenient data structures `std::set` and `std::map`, which are tree data structures whose operations take $O(\log n)$ time. With C++11, we finally received a hash set and hash map in `std::unordered_set` and `std::unordered_map`. Unfortunately, I've seen a lot of people on Codeforces get hacked or fail system tests when using these. In this post I'll explain how it's possible to break these data structures and what you can do in order to continue using your favorite hash maps without worrying about being hacked [cut] . So how are they hackable? We always assume hash maps are $O(1)$ per operation (insert, erase, access, etc.). But this depends on a key assumption, which is that each item _only runs into $O(1)$ collisions on average_. If our input data is completely random, this is a reasonable assumption. But this is no longer a safe bet when the input isn't random, especially so if someone is adversarially designing inputs to our code (a.k.a. hacking ph...
effectively modulo p, but will be problematic for `gp_hash_table`'s power of two policy; the same, hack them. These hash tables use a modulo power of two policy, so in order to make a lot of, hash tables use a modulo power of two policy, so in order to make a lot of collisions occur we can, ) + 2`, `(3 << 16) + 3`, ..., into this hash table, all of the outputs will be equivalentmodulo $2^16

Full text and comments »

  • Vote: I like it
  • +752
  • Vote: I do not like it

7.
By Errichto, 8 years ago, In English
Sums and Expected Value — part 1 part 2: https://codeforces.me/blog/entry/62792 Watch my lecture-stream tomorrow (Thursday) at [14:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?msg=EV+lecture+1&iso=20181025T14&p1=262) &mdash; <s>[https://www.youtube.com/watch?v=qdlPY37MBPo](https://www.youtube.com/watch?v=qdlPY37MBPo)</s> [https://www.youtube.com/watch?v=U_h3IjreRek](https://www.youtube.com/watch?v=U_h3IjreRek). I will go through theory and problems from this blog. The only prerequisite is knowing what is probability. The next (harder) part on Monday. The video will be available later, with timestamps for each problem &mdash; so you don't have to watch everything. ### Definition of EV Let's say we bought a lottery ticket for 2$. We will win 10$ with probability 10%, and 20$ with p-bility 2%. On average, it gives us $0.1 \cdot 10 + 0.02 \cdot 20 = 1.4$, so we are worse off after buying the ticket. The computed average is called the expected value. The expected value (EV, expecta...
$ possibilities, and print answer modulo $10^9+7$. (This answer divided by $2^N$ gives the answer from the, . Equivalently: Find the sum over total prize over all $2^N$ possibilities, and print answermodulo $10^9+7, : Find the sum over the difference over all subsets, and print the answer modulo $10^9+7$., ^3$ over all intervals. Print the answer modulo $10^9+7$. There are a few possible solutions

Full text and comments »

  • Vote: I like it
  • +614
  • Vote: I do not like it

8.
By zscoder, history, 7 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 2) Welcome to Part 2 of my tutorial on generating functions. The [first part](https://codeforces.me/blog/entry/77468) focused on introducing generating functions to those without any background in generating functions. In this post, I will demonstrate a few applications of generating functions in CP problems. Let us start with some relatively straightforward examples. Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually $998244353$). Also, $[n]$ denotes the set $\\{1,2,...,n\\}$. ### Blatant Applications in Counting Problems **Problem.** [AGC 005 Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices. For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T$ which contains all vertices in $S$. For all $1 \le k \le n$, find the sum of $f(S)$ over all subsets $S$ with $|S| = k$. Constraints: $n \le 2 \cdot 10^{5}$. <spoiler summary="Solution"> First, ...
implementation of it). Here, we can exploit the fact that we are computing the answermodulo $p, us compute our answer as a **polynomial** in $\omega$, but modulo $\omega^{3}-1$ (which means that we, **Problem.** [Sum Modulo](https://codeforces.me/gym/102586/problem/C) You have a number $x$ which, , modulo $10^{9}+7$., /fb0f7a0301acb44f9d8f82c94bd848737ce55e6c) Find the sum $\displaystyle\sum_{i \equiv r \pmod{m}}\binom{n}{i}$modulo an, Compute $d_{n,m}$ modulo $998244353$., It remains to compute $\frac{1}{m}\displaystyle\sum_{j=0}^{m-1}w^{j(m-r)}(1+w^{j})^{n}$modulo $MOD, Note: This problem is also solvable in $O(m\log m\log n)$ if $MOD$ is a FFT-friendlymodulo by, Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually, {i} = n$, modulo $19491001$ (a prime).

Full text and comments »

  • Vote: I like it
  • +518
  • Vote: I do not like it

9.
By Um_nik, 8 years ago, In English
How to read problem statements But [user:Um_nik,2018-10-26], we all know how to read, we have our whooping 2 month of experience! Oh, my sweet summer child, my experiments show that many people with kinda cool achievements like medals on ROI don't know how to read statements. But don't worry, I'll teach you. Well, probably you won't understand anything, because you didn't try to understand anything in your life, you expect all hard work to be done for you by someone else. Let's start! Basic rules ================== - The result of reading the statement is usually pure math model. If story helps to build correct understanding, you can keep it, but still try to discard as many unnecessary details as possible. - Imagine you want to tell the problem to someone else. What parts you want to tell? (According to my PM, this rule won't help you). - Shorter = better. - Simpler = better. - Limitations are part of problem statement. Especially small limitations, because for small data you can try all the possib...
are living modulo $7$. $7$ is prime, that gives us hope. Each sort of honey takes some fixed but, included, sorry"> We are only interested in weekdays, so basically we are livingmodulo $7$. $7, modulo $Q$ and get zero vector modulo $Q$. Or matrix rank modulo $Q$ is less than $n$. Or determinant

Full text and comments »

  • Vote: I like it
  • +381
  • Vote: I do not like it

10.
By cjj490168650, history, 4 years ago, In English
[Repost] "Justice may be delayed, but it cannot be absent": New Evidence on NXIST's Cheating Scandal _Original post: [「正义可以迟来但不能缺席」:关于 NXIST 的一些新证据](https://zhuanlan.zhihu.com/p/620297880)_ _Translated by GPT-4 with some adjustment. Please inform me if there are any mistakes._ _All links to the invalid repository have been redirected to the backup repository._ **This article provides a logically complete set of evidence, which does not involve any non-public internet resources, regarding the "suspected cheating" incident involving the ICPC Yinchuan Station and ICPC Shenyang Station in 2021. By discovering the suspected GitHub account ([NaokiLH](https://github.com/NaokiLH), renamed to https://github.com/brokenTarget) of a team member from Ningxia Institute of Science and Technology (NXIST) TS 1 team, Lan Hao, two years ago, and by mining and analyzing the commit records of his algorithm competition repo, we have obtained direct evidence that at least 4 questions from the 2021 Yinchuan regional contest set and at least 6 questions (including scrapped questions) from the 2021 Sh...
to the template code for outputting the Catalan numbers modulo 1000000007. - [tempo11.cpp](https

Full text and comments »

  • Vote: I like it
  • +1018
  • Vote: I do not like it

11.
By platelet, history, 4 years ago, In English
A modulo multiplication method that is 2x faster than compiler implementation > Given $k,m$ and $n$ numbers $a_i$, compute each $a_i\times k\bmod m$ I came up with a method that is almost twice as fast as the compiler implementation (when $m$ is a constant), which can effectively speed up the NTT and some DPs. First of all $$ a_i\times k\bmod m=\{a_i\times \frac km\}\times m\tag1 $$ where $\\{x\\}=x-\lfloor x\rfloor$ is the fractional part function. The principle of equation $(1)$ is that $a_i\times k\bmod m$ is only related to the fractional part of $\frac{a_i\times k}m$. Let $\frac km\approx\frac p{2^{64}}$, $p$ is either equal to $\lfloor\frac km\times2^{64}\rfloor$ or $\lceil\frac km\times2^{64}\rceil$, which one to choose, we will decide later, then $$ \begin{aligned} a_i\times k\bmod m&\approx\{a_i\times \frac p{2^{64}}\}\times m\\ &=\frac{a_ip\bmod 2^{64}}{2^{64}}\times m\\ &=\frac{a_ip\bmod 2^{64}\times m}{2^{64}} \end{aligned} \tag2 $$ There are two place we need to choose whether round up or down: - $p=\lfloor\frac km\t...
A modulo multiplication method that is 2x faster than compiler implementation, * (__uint128_t)P >> 64; } } end = std::chrono::steady_clock::now(); cout << "My modulo, << "Compiler's signed modulo: " << (end - start).count() * 1e-6 << " ms" << endl;, )a[i] * p` will automatically be modulo $2^{64}$. - `* (unsigned __int128)P >> 64` is 64-bit, - Constant modulo multiplication is almost 4 times faster in parallel than serial (as ismodulo, -bit architecture. - `(unsigned)a[i] * p` will automatically be modulo $2^{64}$. - `* (unsigned, ::steady_clock::now(); cout << "Compiler's signed modulo: " << (end - start).count() * 1e-6 << " ms, ::steady_clock::now(); cout << "Compiler's unsigned modulo: " << (end - start).count() * 1e-6 << " ms, ; } end = std::chrono::steady_clock::now(); cout << "Compiler's unsigned modulo : " << (end, ; } } end = std::chrono::steady_clock::now(); cout << "My modulo: " << (end, Latency test(50000 * 25000): Compiler's signed modulo: 4329.33 ms Compiler's unsignedmodulo, \times50000$ modulo multiplications. - The second part is the Latency, which is the time taken for, ```plain Throughput test(50000 * 50000): Compiler's signed modulo: 1954.83 ms Compiler's

Full text and comments »

  • Vote: I like it
  • +311
  • Vote: I do not like it

12.
By TLE, history, 4 years ago, In English
CPIdeas: use AI to generate competitive programming ideas Hello Codeforces! Being asked to propose competitive programming questions is pretty haunting. When you're out of fresh ideas, I used to do one of the two things. One, is to search in the old pile of problems, hoping to find some room of modifications and improvements. The second, is to come up with random words, like "chessboard inversion counting", and hopefully resemble interesting problems from them. This process is pretty boring, so I have been trying to use machine learning to generate ideas and even complete competitive programming problems. The result is *CPIdeas*! Check it out here: https://fjzzq2002.github.io/cpideas/. *How was it made?* I collected problems from AtCoder (ABC, ARC, AGC) and used these problems to fine-tune GPT-3, the OpenAI model. It's quite tricky to get things right though and it's still far from perfect. *How should I use it?* Look through these ideas. Scroll down. Be tolerant and creative. That's it. *How should I use these ideas?* For the ...
satisfy the following conditions, modulo 998244353. 1<=Ai<=M. There exists a permutation P=(P1,P2

Full text and comments »

  • Vote: I like it
  • +604
  • Vote: I do not like it

13.
By -is-this-fft-, history, 4 years ago, In English
[Tutorial] FFT If I was a YouTuber, this would be the place where I fill the entire screen with screenshots of people asking me to make this. Anyway, not so long ago I gave a lecture on FFT and now [user:peltorator,2023-01-11] is giving away [free money](https://codeforces.me/blog/entry/110840), so let's bring this meme to completion. In this blog, I am going to cover the basic theory and (competitive programming related) applications of FFT. There is a long list of generalizations and weird applications and implementation details that make it faster. Maybe at some point I'll write about them. For now, let's stick to the basics. **The problem.** Given two arrays $a$ and $b$, both of length $n$. You want to quickly and efficiently calculate another array $c$ (of length $2n - 1$), defined by the following formula. $$c_k = \displaystyle \sum_{i + j = k} a_i \cdot b_j.$$ Solve it in $O(n \log n)$. First of all, why should you care? Because this kind of expression comes up in combinatorics a...
leading zeroes. You are given a subset of decimal digits that are allowed. Count,modulo 998244353, things modulo some large prime. Remember that modulo $p$, some polynomial equations are solvable even, $, $\omega^1 = \omega^{m + 1}$ etc. The exponents behave as though we are adding them,modulo $m$. $\omega, **Fact.** A $m$-th primitive root of unity exists modulo a prime $p$ if and only if $p - 1$ is, , calculate modulo 998244353 the number of permutations $p$ of length $n$ such that $p[y] = \max_{i = 1}^y p, The exponents in this matrix are the multiplication table, taken modulo 8 because $\omega^0, modulo 998244353, we can calculate FFTs of length up to $2^{23}$, which is enough for almost all

Full text and comments »

  • Vote: I like it
  • +436
  • Vote: I do not like it

14.
By zscoder, history, 10 years ago, In English
[Tutorial] Non-trivial DP Tricks and Techniques Hi everyone! Today I want to share some DP tricks and techniques that I have seen from some problems. I think this will be helpful for those who just started doing DP. Sometimes the tutorials are very brief and assumes the reader already understand the technique so it will be hard for people who are new to the technique to understand it. Note : You should know how to do basic DP before reading the post DP + Bitmasks ------------------ This is actually a very well-known technique and most people should already know this. This trick is usually used when one of the variables have very small constraints that can allow exponential solutions. The classic example is applying it to solve the Travelling Salesman Problem in $O(n^{2} \cdot 2^{n})$ time. We let $dp[i][j]$ be the minimum time needed to visit the vertices in the set denoted by $i$ and ending at vertex $j$. Note that $i$ will iterate through all possible subsets of the vertices and thus the number of states is $O(2^{n} \cdo...
product of its elements. Find the sum of $value(S)$ for all possible valid sequences $S$,modulo $p

Full text and comments »

  • Vote: I like it
  • +612
  • Vote: I do not like it

15.
By Errichto, 6 years ago, In English
Matrix Exponentiation tutorial + training contest tl;dr &mdash; video tutorial https://www.youtube.com/watch?v=eMXNWcbw75E and codeforces GYM training https://codeforces.me/gym/102644 (register by finding this contest in GYM instead of using the link directly) video editorial: [part 1 (ABCDEF)](https://www.youtube.com/watch?v=kQuCOFzWoa0) and [part 2 (GHI)](https://www.youtube.com/watch?v=RA_SpxP2t54) codes to all 9 problems: https://github.com/Errichto/youtube/tree/master/matrix-exponentiation Prerequisites: binary exponentiation and iterative dp (you don't need to know matrices) The youtube tutorial ([link](https://www.youtube.com/watch?v=eMXNWcbw75E)) focuses on intuition and graph-like visualization . Or, if you prefer, below is a shorter (less detailed) text tutorial instead. You can practice by solving a set of 9 educational problems in GYM https://codeforces.me/gym/102644. ABCD are easy, EF medium, GHI are hard. If you are stuck, see hints below or watch the full solution analysis &mdash; [part 1 (ABCDEF)](https:...
$n$ ($n \leq 10^{18}$), count such strings that Limak will be happy after reading that string,modulo

Full text and comments »

  • Vote: I like it
  • +606
  • Vote: I do not like it

16.
By duality, 3 years ago, In English
Codeforces Round #884 (Div. 1 + Div. 2) Editorial Video editorials for [B](https://www.youtube.com/watch?v=5nzUni8dFLQ), [C](https://www.youtube.com/watch?v=8mz7gnAJ5QM), and [D](https://www.youtube.com/watch?v=ahnNAwpGwHc) are available on [user:ak2006,2023-07-11]'s channel. ### [problem:1844A] <spoiler summary="Hint 1"> There exists a small $n$ where the second player can win. </spoiler> <spoiler summary="Hint 2"> If $a \ge 2$, then $n = 1$ works. </spoiler> <spoiler summary="Solution"> [tutorial:1844A] </spoiler> <spoiler summary="Implementation"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t,a,b; scanf("%d",&t); while (t--) { scanf("%d %d",&a,&b); printf("%d\n",a+b); } return 0; } ~~~~~ </spoiler> ### [problem:1844B] <spoiler summary="Hint 1"> In order for $(l,r)$ to contribute to the primality, we must have $\operatorname{MEX}(a_l,\dots,a_r) \ge 2$, so there is some value $1$ between indices $l$ and $r$. </spoiler> <spoile...
After solving the equations modulo $2$, we can similarly solve modulo, Solve the equations modulo $2$ first, so that the $2x_{\text{lca}(i,i+1, Think of the letters as numbers modulo $3$ and look at, cycles. Only the length of each path/cycle modulo $3$ matters.

Full text and comments »

  • Vote: I like it
  • +379
  • Vote: I do not like it

17.
By -is-this-fft-, history, 4 years ago, In English
On "is this greedy or DP", forcing and rubber bands #### Introduction When it comes to "problem-solving techniques", there are roughly 3 levels: 1. Concrete algorithms (Kruskal's algorithm, Li-Chao tree, fast Fourier transform) 2. General patterns (dynamic programming, greedy, square-root decomposition) 3. Meta-strategies ("how do I even go about solving this problem?") There is some grey area, but in general this classification works well. [Many tutorials](https://codeforces.me/catalog) have been written about ideas that fall into 1 or 2. But very little has been written about the third category. On the catalog, I think the only blogs that really qualify are [this](62730) and [this](20548). There is also [this](92248?#comment-809401) valuable comment. As to why there is so little written, I think I can identify two reasons. - Most strong contestants don't really consciously think about these. After solving a problem with FFT, it's hard not to know you used FFT. If you used DP, even if you did it without thinki...
only the positions that give 1 modulo $b$. Exactly one bit changes there too. And so on., Let's divide the positions into buckets by their indices modulo $b$. Every time we do an operation

Full text and comments »

  • Vote: I like it
  • +548
  • Vote: I do not like it

18.
By adamant, history, 4 years ago, In English
Computing n! modulo pᵏ for small p Hi everyone! There is an [article](https://cp-algorithms.com/algebra/factorial-modulo.html) on cp-algorithms about how to compute $n!$ modulo prime number $p$. Today I was wondering, how to do it if we need to compute modulo $p^k$ rather than just $p$. Turns out one can do it efficiently if $p$ is small. #### Motivational example **[Xiaoxu Guo Contest 3 &mdash; Binomial Coefficient](https://www.acmicpc.net/problem/19124)**. Given $1 \leq n,k \leq 10^{18}$, find $\binom{n}{k}$ modulo $2^{32}$. There are also some projecteuler problems that require it, including with several queries of distinct $n$ and $k$. #### Task formulation and outline of result To clarify the task a bit, our ultimate goal here is to be able to compute e.g. binomial coefficients modulo $p^k$. Thus, what we really need is to represent $n! = p^t a$, where $\gcd(a, p)=1$, and then report $t$ and $a$ modulo $p^k$. This is sufficient to also compute $\binom{n}{r}$ modulo $p^k$. We will show that, ass...
Computing n! modulo pᵏ for small p, $p=2$ when $z$ has remainder $3$ modulo $4$. It is accounted for in the code by tracking the number, about how to compute $n!$ modulo prime number $p$. Today I was wondering, how to do it if we need to, coefficients modulo $p^k$. Thus, what we really need is to represent $n! = p^t a$, where $\gcd(a, p)=1$, and, cp-algorithms about how to compute $n!$ modulo prime number $p$. Today I was wondering, how to do it, !_p$ modulo $p^k$ in advance in $O(p^k)$ for all $a < p^k$, which then allows us to compute the full, )$ operations, and assuming that arithmetic operations modulo $p^k$ take $O(1)$, we can find $t$ and $a$ in, )**. Given $1 \leq n,k \leq 10^{18}$, find $\binom{n}{k}$ modulo $2^{32}$.

Full text and comments »

  • Vote: I like it
  • +135
  • Vote: I do not like it

19.
By Sparky_Master_WCH1226, history, 21 month(s) ago, In English
Problem of cheating in Competitive Programming You are probably already familiar with the following cheating methods, submitting your solution on alt account, with 4o, and then deep seek, and then o1, and then o3, finding solutions on telegram, finding solutions on youtube, finding solutions on discord, asking your blue rated friend, asking your purple rated friend, asking your orange rated friend, asking your red rated friend, asking your lgm rated friend, play as a team of cyan, play as a team of blue, play as a team of purple, play as a team of orange, play as a team of red, play as a team of lgm, asking some other blue that is not your friend, asking some other purple that is not your friend, asking some other orange that is not your friend, asking some other red that is not your friend, asking some other Lgm that is not your friend, pay an orange to play the contest for you, pay a red to play the contest for you, pay an LGM to play the contest for you, print out katcl and bring it to IOI, print out cp-algorithm and bring it to...
Count the number of ways to cheat, as cheating could be huge, output it modulo 998244853

Full text and comments »

  • Vote: I like it
  • +706
  • Vote: I do not like it

20.
By Phantasmagorias, history, 5 years ago, In English
Codeforces Round #745 Editorial I'm very sorry about all the inconvenience, and I would like to bear the blame. Much thanks to those who help me prepare this round. It's not their fault. And much thanks to your participation. [problem:1581A] ------------------ idea: [user:interlude,2021-09-30] preparation: [user:CQXYM,2021-09-30] tutorial: [user:CQXYM,2021-09-30] Assume a permutation $p$, and $\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\forall 1 \leqslant i \leqslant 2n, q_i=2n-p_i$. We can know that $\forall 2 \leqslant i \leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ should be counted. All in all, the half of all the permutaions would be counted in the answer. Thus, the answer is $\frac{1}{2}(2n)!$. The time complexity is $O(\sum n)$. If you precalulate the factors, then the complexity will be $O(t+n)$. ----- <spoiler summary="solution"> ~~~~~ #include<stdio.h> int f[100001]; int m...
that satisfy $x_i + y_i = a$ are in maintenance modulo $a$. And for one period of maintenance, the

Full text and comments »

  • Vote: I like it
  • +799
  • Vote: I do not like it

21.
By adamant, history, 5 years ago, In English
p-adic exponent or why there is a primitive root modulo powers of prime numbers (except 2) Hi everyone! You probably know that the primitive root modulo $m$ exists if and only if one of the following is true: - $m=2$ or $m=4$; - $m = p^k$ is a power of an odd prime number $p$; - $m = 2p^k$ is twice a power of an odd prime number $p$. Today I'd like to write about an interesting rationale about it through $p$-adic numbers. Hopefully, this will allow us to develop a deeper understanding of the multiplicative group modulo $p^k$. ### Tl;dr. For a prime number $p>2$ and $r \equiv 0 \pmod p$ one can uniquely define $$ \exp r = \sum\limits_{k=0}^\infty \frac{r^k}{k!} \pmod{p^n}. $$ In this notion, if $g$ is a primitive root of remainders modulo $p$ lifted to have order $p-1$ modulo $p^n$ as well, then $g \exp p$ is a primitive root of remainders modulo $p^n$. Finally, for $p=2$ and $n>2$ the multiplicative group is generated by two numbers, namely $-1$ and $\exp 4$. [cut]<br> ### $p$-adic numbers We define a $p$-adic number $r$ as a formal po...
p-adic exponent or why there is a primitive root modulo powers of prime numbers (except 2), $\alpha(r)$, making up for $(p-1)p^{k-1}$ different invertible numbers modulo $p^k$. If we were to, multiplicative group of remainders modulo $p^k$ in additive terms. Let's recall the power series, that they're taken modulo $p-1$ and all meaningful values of $\alpha$ are generated by the multiples, $, traversing all remainder modulo $p^k$ that are divisible by $p$., Any invertible remainder modulo $p^k$ can be represented as $r \equiv g^{l}t \pmod{p^k}$, where $t, As such, it means that powers of $\log 4$ generate all the numbers that are equal to $1$modulo $4, As we mentioned earlier, $\exp r$ is still well-defined for $r \equiv 0 \pmod 4$, somodulo $2^k, Hi everyone! You probably know that the primitive root modulo $m$ exists if and only if one of, Hopefully, this will allow us to develop a deeper understanding of the multiplicative groupmodulo, In this notion, if $g$ is a primitive root of remainders modulo $p$ lifted to have order $p-1, Note that there are $p^{k-1}$ numbers $x$ (taken modulo $p^k$) such that $x \equiv 1 \pmod p$, as, Therefore the whole multiplicative group of remainders modulo $2^k$ is generated by $-1$ and $\exp, This, in turn, means that all remainders modulo $p^k$ are generated by the $p$-adic number $g \exp, You probably know that the primitive root modulo $m$ exists if and only if one of the following is, and treat the $p$-adic number as nested set of remainders modulo $p^k$ for increasing $k$, which is

Full text and comments »

  • Vote: I like it
  • +155
  • Vote: I do not like it

22.
By dacin21, history, 8 years ago, In English
On the mathematics behind rolling hashes and anti-hash tests This blog assumes the reader is familiar with the basic concept of rolling hashes. There are some math-heavy parts, but one can get most of the ideas without understanding every detail. The main focus of this blog is on how to choose the rolling-hash parameters to avoid getting hacked and on how to hack codes with poorly chosen parameters. # Designing hard-to-hack rolling hashes ## Recap on rolling hashes and collisions Recall that a rolling hash has two parameters $(p, a)$ where $p$ is the modulo and $0 \leq a < p$ the base. (We'll see that $p$ should be a big prime and $a$ larger than the size $\left|\Sigma\right|$ of the alphabet.) The hash value of a string $S = s_0 \dots s_{n-1}$ is given by $$ h(S) := \left(\sum\limits_{i=0}^{n-1} a^{n-1-i} s_i\right) \mod p $$ For now, lets consider the simple problem of: given two strings $S, T$ of equal length, decide whether they're equal by comparing their hash values $h(S), h(T)$. Our algorithm declares $S$ and $T$ t...
with overflow | $\Theta(1)$ | $2^10$ | Works for all bases simultaneously. Birthday | Smallmodulo, ## Randomizing modulo, ### Larger modulo, ) # modulo reductions m.set_block(N, 0, MULTIPLIER * diagonal_matrix(Ps)) # term, def h(s): """polynomial hash modulo primes""" v = [0] * n for c in s, modulo.

Full text and comments »

  • Vote: I like it
  • +371
  • Vote: I do not like it

23.
By -Morass-, history, 9 years ago, In English
Problem Topics Good Day to you! I've been asked to make some topic-wise list of problems I've solved. Even though I couldn't involve all problems, I've tried to involve at least "few" problems at each topic I thought up (I'm sorry if I forgot about something "easy"). I've alredy made such list once anyway I've tried to include more problems now &mdash; so here it is: <spoiler summary="aho"> http://www.spoj.com/problems/ADAJOBS/ URI 2226 (5) //[NICE][NUMBERS][DP] http://www.spoj.com/problems/SUB_PROB/en/ http://codeforces.me/contest/696/problem/D 8 http://www.spoj.com/problems/AHOCUR/ 5 //Aho-Corassic + DP https://www.codechef.com/problems/LYRC (5) //Sample aho-brute-force http://codeforces.me/problemset/problem/346/B //Proposed by [user:bradyawn,2019-08-03] </spoiler> <spoiler summary="automat"> 6861 [LA] //CYK UVA 10679 //Suffix Automat http://www.spoj.com/problems/STRMATCH/ //Suffix Automat &mdash; trie might do too http://www.spoj.com/problems/NSUBST...
http://codeforces.me/contest/110/problem/B (2) //Easy modulo, http://codeforces.me/contest/46/problem/A (2) //[EASY][MODULO], http://codeforces.me/contest/78/problem/B (2) //NICE — last 3 and then rest in modulo, http://codeforces.me/contest/825/problem/D (3) //Update by modulo, http://codeforces.me/contest/85/problem/A (3) //MODULO / SHIFT, http://codeforces.me/contest/876/problem/B (3) //Group by modulo, http://codeforces.me/contest/920/problem/D (4) //[NICE][KNAPSACK-MODULO ][GREEDY], http://codeforces.me/gym/101597/problem/A (4) //[MATH][MODULO][SIMULATION], http://www.spoj.com/problems/GUMATH2/ (4) //A000240 Modulo by MOD*2, http://www.spoj.com/problems/SKYLINE/ (3) //Catalan numbers [weird modulo — care], https://codeforces.me/contest/1176/problem/B (2) //[MODULO][GREEDY], https://codeforces.me/contest/1180/problem/C (4) //[MODULO][QUEUE], https://codeforces.me/contest/1181/problem/A (2) //[EASY][FORMULA][MODULO]

Full text and comments »

  • Vote: I like it
  • +428
  • Vote: I do not like it

24.
By pajenegod, history, 3 years ago, In English
Tutorial: A simple O(n log n) polynomial multiplication algorithm Hi Codeforces! I have something exciting to tell you guys about today! I have recently come up with a really neat and simple recursive algorithm for multiplying polynomials in $O(n \log n)$ time. It is so neat and simple that I think it might possibly revolutionize the way that fast polynomial multiplication is taught and coded. You don't need to know anything about FFT to understand and implement this algorithm. Big thanks to [user:nor,2023-07-10], [user:c1729,2023-07-10] and [user:spheniscine,2023-07-10] for discussing the contents of the blog with me and comming up with ideas for how to improve the blog =). I've split this blog up into two parts. The first part is intended for anyone to be able to read and understand. The second part is advanced and goes into a ton of interesting ideas and concepts related to this algorithm. Prerequisite: Polynomial quotient and remainder, see [Wiki article] (https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Euclidean_divi...
This algorithm requires three, using modulo a prime (or more generally modulo an odd composite number)., This implementation is based on the polynomial modulo multiplication algorithm.

Full text and comments »

  • Vote: I like it
  • +349
  • Vote: I do not like it

25.
By pajenegod, history, 6 years ago, In English
(Request) Update PyPy's Version on CF I've always liked using Python (PyPy) for solving problems in competitive programming. And most problems are very doable, even in Python. What I've found is that the most difficult problems to solve in Python are those requiring 64 bit integers. The reason why 64 bit integers are problematic is because CF runs Windows, and PyPy only supports 32 bit on Windows. So whenever a problem involves integers that cannot fit inside of a signed 32 bit int, PyPy switches to big integers (which runs insanely slow, sometimes a factor of 20 times slower). <spoiler summary="What I currently have to do to get around big integers"> ### 1. Switching to floats What I usually try is switching from using integers to floats. This works if all integers are $\leq 2^{52}$: [submission:53441394] (Fat TLE and almost MLE) vs [submission:53456822] (AC by a mile) ### 2. Calculating `a * b % MOD` Many problems on CF involve doing multiplication modulo $10^9 + 7$. This is super slow because of big integ...
### 2. Calculating `a * b % MOD` Many problems on CF involve doing multiplicationmodulo $10^9 + 7

Full text and comments »

  • Vote: I like it
  • +642
  • Vote: I do not like it

26.
By errorgorn, 5 years ago, In English
On Div2ABs 2 years ago, [user:antontrygubO_o,2022-04-27] wrote [a blog](https://codeforces.me/blog/entry/75163) about div2ABs where he expressed his opinions that d2ABs should not be about "here is a statement, please implement what is written there". Thanks to him, the quality of d2ABs (and problem quality in general) have certainly improved. However, I still believe that there still quite large differences between how coordinators/problemsetters view d2ABs and how the intended participants view them. From the survey made by [user:kpw29,2022-04-27], we can see that most people agree that most people agree that we should **primarily** consider the target audience when proposing a task. I too think if a task is boring to div 1 contestants, we should not think of that as a reason to immediately disqualify a problem from being a d2A. ![ ](https://codeforces.me/predownloaded/70/b5/70b515da85a4dc3b362cf4eb0963dbd1fb642819.png) I think when people judge the interesting-ness of d2As, they try...
A but ok for a B, no computer science involved, requires to know modulo operations. (accepted as a, , many people may be new to modulo operations, I don't think that they are very suitable for an A., [user:Um_nik,2022-04-27]: counting anything modulo is probably a bit hard for div2A, but this one

Full text and comments »

  • Vote: I like it
  • +330
  • Vote: I do not like it

27.
By DrSwad, history, 7 years ago, In English
A Beautiful Technique for Some XOR Related Problems ## Inspiration I'm very excited about this blog, as it took me quite a lot of effort and scavenging through the internet to completely grasp the concept of this technique(That's probably because I have almost zero knowledge in Linear Algebra or I'm just plain dumb). So I feel like I genuinely conquered a challenge, and I really want to share it with someone. But there's no way my CP friends circle will believe it, they'll think I'm just trying to show off :P So here I am, sharing it on CF. I also created a [personal blog](https://drschwad.github.io/), so that if I ever feel like sharing something again(not only about CP), I can write a blog there. I also added this same post [there](https://drschwad.github.io/2019-08-06-z2-space-xor-trick/), you can read it there if you prefer dark theme. I'll be pleased to hear any thoughts on the blog or if I can improve it in some way ^\_^ ## Introduction Since it concerns Linear Algebra, there needs to be a lot of formal stuff going on ...
\lt 2^{20}.$ Find the number of subsequences of the first $l$ elements of this array,modulo $10^9, coordinates get added modulo $2,$ which actually gives us the position vector of the xor of these two position, the result of their sum taken modulo $2$:, > Find the number of non-empty subsets, modulo $10^9 + 7,$ of a given set of size $1 \le n \le 10^5, This is all there is to it. Transforming xor operations to bitwise addition modulo $2$ and, in some, modulo $2.$

Full text and comments »

  • Vote: I like it
  • +425
  • Vote: I do not like it

28.
By purplesyringa, history, 5 years ago, In English
Analysis of polynomial hashing Unfortunately, most derivations of the chance of polynomial hashing collision are invalid, wrong, or misleading, and finding reliable public sources with proofs is incredibly difficult. This article is a formal analysis of the method. The goal of this article is to complement well-known empirical facts with theory, provide boundaries on the probability of collision, justify common choices, and advise against certain popular parameters. There is no code in this article, and it's mostly theoretical. It's more of a summa of everything we know about polynomial hashing in integers rather than a guide for beginners. You'll probably find something of interest still. I do, however, describe some methods of cracking hashes, which I can provide code and additional explanation for if someone asks in the comments and some general guidelines in the last section of the present article. ## Table of contents - The concept of polynomial hashing - Classical justification of the coprimality r...
\vert M$ all elements of $\Sigma$ are congruent modulo $p$, $H$ is not surjective., expected to be zero modulo $p$ for all $b$, this is a reasonable choice modulo $2$, but it's, has $\frac{M}{(b, M)}$ solutions modulo $M$. If $x$ was added to $u_2$, there would be $\frac{M}{(b^2, polynomials with the same remainder modulo $x - b$, and this is a key to generating universal collisions., same remainder modulo $P(x)$, they generate a collision for all $b$ in $\\{b_1, b_2, \dots, b_k, , so we take the result modulo $M$. This means all hashes fit within a finite integral type, but hash, - If $b = 1 \pmod 3$, only parentheses of kind $1 - b$ are zero modulo 3. - If $b = 2 \pmod 3$, $1, As $b \perp M$, $b$ is invertible modulo $M$ and hence the equation can be rewritten as, The trick behind the Thue-Morse sequence is that $1 + b^x$ is always zero modulo $2$, and then we, This also gives a condition on moduli for double hashing. Double hashing modulo $M_1$ and $M_2$ is

Full text and comments »

  • Vote: I like it
  • +308
  • Vote: I do not like it

29.
By Endagorion, 12 years ago, translation, In English
Codeforces Round #283: editorial (with bonuses!) Each problem comes with a challenge &mdash; a bonus task somehow related to the problem; you may tackle at the challenges for fun and practice, also feel free to discuss them at the comments. =) [problem:496A] For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^2)$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the difference between the neighbours of the removed element (whatever is larger); thus, the difficulty for every option of removing an element can be found in $O(1)$, for the total complexity of $O(n)$. Any of these solutions (or even less efficient ones) could pass the tests. **Challenge**: suppose we now have to remove exactly $k$ arbitrary elements (but the first and the last elements have to stay in their places). How small the maximal difference between adjacen...
$ modulo $k$ to all elements of the part. Let us count the matrices (see above) for the prefixes of length, **Challenge**: compute how many (say, modulo $10^9 + 7$) $n \times m$ tables are there for which

Full text and comments »

  • Vote: I like it
  • +336
  • Vote: I do not like it

30.
By Endagorion, 12 years ago, In English
Codeforces Round #300 Editorial (+challenges) As usual, a challenge comes with every problem. I tried not to repeat the mistakes of my previous editorials and made sure that all challenges have a solution =) (except for the _italics_ parts that are open questions, at least for me). Go ahead and discuss them in the comments! General questions about problems and clarification requests are welcomed too. **UPD**: I added codes of my solutions for all the problems. I didn't try to make them readable, but I believe most part of them should be clear. Feel free to ask questions. [problem:538A] Let me first clarify the statement (I really wish I didn't have to do that but it seems many participants had trouble with the correct understanding). You had to erase exactly one substring from the given string so that the rest part would form the word `CODEFORCES`. The (somewhat vague) wording `some substring` in the English translation may be the case many people thought that many substrings can be erased; still, it is beyond my understa...
$), determine how many (modulo a prime number) integer sequences of length $n$ with the property $|h_i, **Challenge (easy)**. A somewhat traditional question: how many (modulo some prime number) large, **Challenge (kinda hard)**. Under the same statement, how many (modulo a prime number) different

Full text and comments »

Tutorial of Codeforces Round 300
  • Vote: I like it
  • +312
  • Vote: I do not like it

31.
By ChthollyNotaSeniorious, history, 4 years ago, In English
Polynomial Round 2022 (Div. 1 + Div. 2) Editorial Thanks for your participation! I am so sorry for my careless review. We were preparing for this round for many months and made some problems which writers and testers are all like. We do want to give everyone a good time to enjoy the contest. But carelessness is deadly. In problem B, some test cases should have been made, but we missed them in not only the pretests but also the final tests. In fact, we had not noticed it until some suspicious hacks appeared. I and all co-authors sincerely regret our mistake and hope you can forgive us. Besides, few people are cyberbullying authors, please do not do so. If you have a bad experience, you can downvote me because of our fault. [problem:1774A] Idea: [user:cirno_9baka,2022-12-17] <spoiler summary="Solution"> The answer is the number of $1$s modulo $2$. We can get that by adding '-' before the $\text{2nd}, \text{4th}, \cdots, 2k\text{-th}$ $1$, and '+' before the $\text{3rd}, \text{5th}, \cdots, 2k+1\text{-th}$ $1$. </spoiler...
The answer is the number of $1$s modulo $2$.

Full text and comments »

32.
By adamant, history, 18 months ago, In English
Finding a billion factorials in 60 ms with SIMD Hi everyone! _This blog is not about asymptotic optimization. Refer to [this comment](https://codeforces.me/blog/entry/63491?#comment-474051) for those._ There is a problem on Library Checker that goes as follows: <hr> **[Many Factorials](https://judge.yosupo.jp/problem/many_factorials)**: You're given $n_1,\dots,n_t$, where $t \leq 10^5$. For each $i$, find $n_i! \bmod M$, where $M = 998\;244\;353$. <hr> In this blog, we will learn how to solve this task in 61 ms, without precalc and **without** FFT. That's right, we will take the dumbest solution we can imagine, and will improve its constant factor until its decent enough. How much decent? Well, let's use the following baseline: <spoiler summary="Naive solution"> ```cpp vector<int> facts(vector<int> args) { const int block = 1 << 16; vector<int> args_per_block[mod / block + 1]; vector<int> res(size(args)); for(auto [i, x]: args | views::enumerate) { args_per_block[x / block].push_b...
In particular, for quick power of $2$ modulo $p$, we can pre-compute powers of $2$ and of $2^{2^{16

Full text and comments »

  • Vote: I like it
  • +274
  • Vote: I do not like it

33.
By PrinceOfPersia, 12 years ago, In English
Codeforces Round #299 Editorial ### [problem:535A] First of all check if $n$ is one of the values $0, 10, 11, …, 19$. Then, let’s have array $x[]$ = {"", "", "twenty", "thirty", …, "ninety"} and $y[]$ = {"", "one", …, "nine"}. ![ ](http://espresso.codeforces.com/d5f38500e79e3e89be0519dc22736124c000bada.png) Let $a = \frac{n}{10}$ and $b = n\ modulo\ 10$. If $n$ is not one of the values above, then if $a=0$, print $y[b]$, else if $b=0$ print $x[a]$ otherwise print $x[a]$-$y[b]$. Time complexity: $O(1)$ [Code](http://ideone.com/mytb2L) by [user:SoroushE,2015-04-02] [Another Code](http://ideone.com/CqgNe5) by [user:PrinceOfPersia,2015-04-05] [Another Code](http://ideone.com/dqiMNL) by [user:Haghani,2015-04-08] [Python Code](http://ideone.com/6tZmNF) by [user:Zlobober,2015-04-04] ### [problem:535B] Sol1: Consider $n$ has $x$ digits, $f(i) = $ decimal representation of binary string $i$, $m$ is a binary string of size $x$ and its $i-th$ digit is 0 if and only if the $i-th$ digit of $...
Let $a = \frac{n}{10}$ and $b = n\ modulo\ 10$.

Full text and comments »

  • Vote: I like it
  • +245
  • Vote: I do not like it

34.
By adamant, 7 years ago, In English
Recovering rational number from its remainder modulo huge integer Hi everyone! It's been a while since I posted anything. Today I'd like to talk about [problem I](https://codeforces.me/gym/102354/problem/I) from [Oleksandr Kulkov Contest 2](https://codeforces.me/blog/entry/72656). Well, on some similar problem. Problem goes as follows: There is a rational number $x=\frac{p}{q}$, and you know that $1 \leq p, q \leq C$. You want to recover $p$ and $q$ but you only know number $r$ such that $r \equiv pq^{-1} \pmod{m}$ where $m > C^2$. In original problem $m$ was not fixed, instead you were allowed to query remainders $r_1,\dots,r_k$ of $x$ modulo several numbers $m_1,\dots,m_k$, which implied Chinese remainder theorem. <br> [cut] <br> To solve this problem let's start with the observation that we always can recover answer uniquely. Indeed, assume that there are numbers $p'$ and $q'$ such that $1 \leq p',q' \leq C$ and $p'q'^{-1} \equiv r \pmod{m}$. That would mean that $pq'\equiv p'q \pmod{m}$. But initial constraints claim that $C^2 < m$, thus...
Recovering rational number from its remainder modulo huge integer, $ was not fixed, instead you were allowed to query remainders $r_1,\dots,r_k$ of $x$modulo several, , instead you were allowed to query remainders $r_1,\dots,r_k$ of $x$ modulo several numbers $m_1, To solve it we should look on how $q, 2q, 3q, \dots$ sequence behaves modulo $m$. We may see that, You can clearly see that while the main progression has a step $3$ modulo $7$, there is also a

Full text and comments »

  • Vote: I like it
  • +182
  • Vote: I do not like it

35.
By bicsi, history, 4 weeks ago, In English
Optimal Incremental MST in 20 lines of code Hello Codeforces! Some of you might know `BottleneckTree.h` from [my KACTL fork](https://github.com/bicsi/kactl/blob/master/content/graph/BottleneckTree.h) (although it's a little obscure for an ICPC notebook; oh well). [user:freak93,2026-11-05] and I wrote it in 2021. The header says the complexity is "probably $O(\log n)$ amortized". It all started from a 2020 solution by [user:RestingRajarshi,2026-11-05] (more on that at the end). After about 6 years of on-and-off thinking about it, and with the help of Claude, we finally have an answer: it's not :). There are inputs where it takes $\Omega(\sqrt n)$ per operation. The good news is that a small change in the main loop fixes it, and this time we have a proof. We wrote a paper about it: [Incremental Minimum Spanning Trees on a Napkin](https://arxiv.org/abs/2611.05713). I think the structure is super elegant and short enough to be useful in contests, so I'm writing a blog about it. Prerequisites: none, really. It helps to know ...
: for $r = L-1, \ldots, 0$, all vertices equal to $r$ modulo $L$, in decreasing order. Then $1, 2

Full text and comments »

  • Vote: I like it
  • +351
  • Vote: I do not like it

36.
By -is-this-fft-, history, 5 years ago, In English
[Math note] On the relationship between gf and me Today, I want to talk a bit about the relationship between two well-known methods for calculating the $n$-th term of a linear recurrence: **g**enerating **f**unctions and **m**atrix **e**xponentiation. More specifically, I want to explore how these two things are related to one another or how they can be thought of as variants of one another. This blog shouldn't be treated as a tutorial. If you know these algorithms, I doubt that I can teach you to solve some new problem in this blog. Rather, I'm kind of thinking out loud. I think it is a good idea to try to reflect and find connections between different things we have learned. This kind of thinking tends to strengthen the understanding of both methods and makes it easier to improve upon them to solve problems. And I'm sure that what I'm about to present is already quite well-known to some people ;). But when I realized this it was cool to me, so I want to share it. **Problem.** You have two sequences $b_1, b_2, \l...
The numbers $\phi$ and

Full text and comments »

  • Vote: I like it
  • +313
  • Vote: I do not like it

37.
By Geothermal, history, 6 years ago, In English
Codeforces Round #709 / Technocup 2021 Final Round - Unofficial Editorial As the editorial for round #709 has yet to be released, I thought I'd write up and post my solutions to the problems (with the exception of Div. 1 F). My code may not be especially useful, since it's a bit messier than necessary in some cases, but I'm hoping that the written explanations will be fairly helpful. Feel free to comment if you have any questions! --- #[2A &mdash; Prison Break](https://codeforces.me/contest/1484/problem/A) By simply playing around with a few small test cases, you might guess that the answer is always equal to $ab$. This intuition is correct; let's prove it formally. Consider a graph with $ab+1$ vertices including one vertex representing each cell of the prison, one vertex representing the outside world, and an edge for each wall of the prison connecting the two vertices on either side of the wall. Then, observe that a set of walls we can remove such that the outside world is accessible from every cell is equivalent to a set of edges that s...
#[2B — Restore Modulo](https://codeforces.me/contest/1484/problem/B), Let $d_i = a_{i+1} - a_i.$ The key observation is that $c$ must be congruent to $d_i$modulo $m

Full text and comments »

  • Vote: I like it
  • +207
  • Vote: I do not like it

38.
By errorgorn, 5 years ago, In English
Generalized FWHT: How I realized I did not understand FWHT I would like to preface this blog by saying this is not a tutorial on FWHT but some (maybe obvious) observations on FWHT that I wanted to share. Thanks to [user:rama_pang,2021-10-15] and [user:oolimry,2021-10-15] for proof reading. Love you guys <3 Of course I (and the proof-readers) are not perfect so if you find anything unclear just tell me in the comments. ![ ](https://cdn.discordapp.com/attachments/752406106009239585/898378522899402772/unknown.png) We will use the symbols $\\&,|,\oplus$ to represent bitwise and, bitwise or, bitwise xor respectively. ## FWHT Given $2$ arrays $A$ and $B$. We will want to find array $C$ such that $C_i=\sum\limits_{j \star k=i} A_j \cdot B_k$. For our normal FFT, the operation $\star$ is just addition. When finding fast for FFT, I found library code that does FWHT $^{[1]}$, that is it does the above operation where $\star$ can also be any of the $3$ bitwise operations. We focus on the case for $\oplus$. We focus even more spe...
do our "FWHT" with other things such as addition modulo $3$ with the matrix $T=\begin{pmatrix, What I did not realize was that $\oplus$ was literally addition under modulo $2$. That is, we were

Full text and comments »

  • Vote: I like it
  • +293
  • Vote: I do not like it

39.
By Endagorion, history, 9 years ago, In English
Yandex.Algorithm 2017, third elimination round: editorial (with challenges, bells and whistles) This time I've decided to play with spoilers to faciliate the presentation as some of the guys here did before. Tell me what you think about this write-up! #### Problem A. Shifts Topics: dynamic programming. Summary: the first "hard" problem of the contest. Knowing your basic DP problems helps a lot, but coming up with the precisely correct solution may take a lot of persistence. Solution: Suppose that we are allowed to make left circular shifts as well as right ones. <spoiler summary="Can you solve the problem in this case?"> First of all, making a shift is effectively moving a character to a different position in the string. Clearly, moving a character more than once makes no sense since we could have just moved it to its final destination instead without wasting any operations. Also, it obvious that the number of occurences of each character should be the same in both strings since it is preserved by shifts. Now, consider the characters that are *not* moved by ...
How many (modulo $10^9 + 7$) positive numbers are there that

Full text and comments »

  • Vote: I like it
  • +255
  • Vote: I do not like it

40.
By errorgorn, 5 years ago, In English
[Tutorial] Knapsack, Subset Sum and the (max,+) Convolution **Edit**: I have realized that this blog has been sent quite a lot on discord servers, so I am adding a content page at the start to help organize this blog better. ## Prerequisites Let us first define the classical knapsack, unbounded knapsack and subset sum problems. #### Subset Sum There are $N$ items. The $i$-th item has weight $w_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i = C$. #### Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. #### Unbounded Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a **multiset** $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. You should know how to do both versions of knapsack in $O(NC)$ and subset sum in $O(\frac{NC}{32})$ before reading this blog. In this blog post, I will just show some res...
,v_1+v_2,\ldots]$ on each residue class modulo $w_i$. We will perform $w_i$ convolutions and each

Full text and comments »

  • Vote: I like it
  • +345
  • Vote: I do not like it

41.
By peltorator, 7 months ago, In English
So Do You Really Understand Fast Matrix Multiplication? Most of you have probably heard of $\omega$, the matrix multiplication exponent. Are you sure you fully understand its definition, though? I thought so too, until I started asking myself some uncomfortable questions and realized that I had some subtle misconceptions. To answer these questions, I read a bunch of papers and book chapters, and now I have some peace of mind. Let me try to scare you a bit first and then hopefully rebuild your understanding of fast matrix multiplication. Let's start with four questions. Try to answer them before reading further. Q1: Does there exist an $O(n^{\omega})$-time matrix multiplication algorithm? Q2: Does there exist an $o(n^{\omega})$-time matrix multiplication algorithm? Q3: Does there exist an $O(n^{\omega + 0.1})$-time algorithm for integer matrix multiplication? Q4: Does there exist an $O(n^{\omega - 0.1})$-time algorithm for integer matrix multiplication? <spoiler summary="Answers"> A1: Maybe. We don't know. A2: ...
rational, we can reduce the whole computation modulo some suitable prime $p$. The prime should just not

Full text and comments »

  • Vote: I like it
  • +379
  • Vote: I do not like it

42.
By gojira, 5 years ago, In English
A look at Competitive Programming post-hibernation Hello friends! As I've recollected in a previous [post](https://codeforces.me/blog/entry/97566), I am an old competitor who hadn't really participated since ~2014, and recently got a bout of nostalgia to return to Competitive Programming. So, I did a couple Topcoder SRMs, suffered through some SNWS rounds, participated in [three regional 5hr competitions](https://contest.yandex.ru/3QF2021) on three consecutive days, and dozed off at every Codeforces contest I tried to wake up for. A lot of things are still the same as 8 years ago: [user:tourist,2022-01-26] is still at the top, grey coders still ask for how many minutes to solve a problem before reading the editorial, Russian university teams [continue winning](https://icpc.global/worldfinals/results) ACM ICPC, and Snarknews never gives up on his alternate competition formats. But in this post, I want to focus on the new patterns that emerged since my last time around. #### #1: Codeforces rounds timing Did you know that t...
10 different problems requesting the answer modulo..., value modulo a large prime. The most common reason for this is that we are counting the number of, #### #5: Probabilities modulo MOD One of my favorite topics in programming contests was always, Most probability theory-related problems I've seen in the past months request the answermodulo

Full text and comments »

  • Vote: I like it
  • +371
  • Vote: I do not like it

43.
By TheScrasse, 12 months ago, In English
Codeforces Round 1066 (Div. 1 + Div. 2) Editorial [problem:2157A] Author: [user:TheScrasse,2025-11-22]<br> Preparation: [user:TheScrasse,2025-11-22] <spoiler summary="Hint 1"> Each value $x$ is independent of the others; only its own frequency matters. </spoiler> <spoiler summary="Hint 2"> In a balanced array, value $x$ must appear either $0$ times or **exactly** $x$ times. </spoiler> <spoiler summary="Solution"> - Each value $x$ is independent of the others; only its own frequency matters. In particular, for each value, find its frequency $f[x]$. - In a balanced array, value $x$ must appear either $0$ times or **exactly** $x$ times. Specifically, if it appears $< x$ times at the beginning, you have to delete all its occurrences, otherwise you should keep $x$ occurrences. Specifically, for each $x$, add $f[x]$ to the answer if $f[x] < x$, else add $f[x] - x$. Complexity: $O(n)$ time. Slower solutions (e.g., $O(n^2)$) are allowed. </spoiler> <spoiler summary = "Code"> [submission:350380351] </spoiler> [...
Try with a different modulo. , You can fix your skill modulo $2$, then modulo $4$, then modulo $8, - Fix our skill modulo $2$ using operations $n-1, n-3, n-5, \ldots$ - Fix our skillmodulo $4, - Fix our skill modulo $3$ using operations $n-2, n-5, n-8, \ldots, n-1, n-4, n-7, \ldots$ - Fix, If we use modulo $m$, we have $\approx \log_m n$ layers, each with cost $\approx n$, and $m-1

Full text and comments »

  • Vote: I like it
  • +82
  • Vote: I do not like it

44.
By errorgorn, 3 years ago, In English
Confession: I sent problem H to goodbye Going to be 100% honest here, I sent problem H to goodbye. I feel really bad to authors of Goodbye 2023 for ruining their round, it seems the round would have been better by just removing H. As much as the community is out here roasting [user:74TrAkToR,2023-12-31], I also had a part to play in this contest. I wish to be as transparent as I can here without saying any classified information (apologies to [user:KAN,2023-12-31] and [user:74TrAkToR,2023-12-31] if anything here shouldn't be disclosed). To give some context, here is what went down in goodbye round from my perspective: - 13 days before contest: KAN asks me if I can source a 1E for goodbye. I asked traktor to send me the testing gym so that I could gauge how hard the 1E should be. He told me he will send me after he translates the statements. (UPD: Note that the IMO 1986 problem was already removed before this stage which is why a new 1E was needed, I never saw this IMO problem) - 11 days before contest: traktor send it...
is what to do when p has a small order modulo 998" . In a discord group chat with [user:endagorion

Full text and comments »

  • Vote: I like it
  • +815
  • Vote: I do not like it

45.
By humbertoyusta, history, 6 years ago, In English
XOR Hashing [TUTORIAL] This is a well known technique, but I couldn't find almost any detailed tutorial, so I'll try to help with this one. ####Motivational Problem: You have an array $A$ and $Q$ queries, which are, say if the subarray from $l$ to $r$, ($A[l]$, $A[l+1]$, $...$, $A[r]$) forms a permutation. ####Some basic observations: Only the set of elements matters, the order is irrelevant. You want to know if each element is exactly once. ####Solution: Assign a random number $randval[i]$ to each number $i$, now we can say that if the XOR of the subarray ( $randval[A[l]]$ xor $randval[A[l+1]]$ xor $...$ xor $randval[A[r]]$ ) is equal to the xor of any permutation of size $r - l + 1$ (for example $1$, $2$, $3$, ... ,$r-l+1$, which hash is $randval[1]$ xor $randval[2]$ xor $...$ xor $randval[r-l+1]$ ) the subarray is a permutation. ####Some Insights: With the XOR we have some issues, we are counting if the number of occurrences of each element is even or odd, not the real number o...
the occurrences of each element modulo $2$ ($x$-character of this string represents the number of, With bitwise-OR we count the number of occurrences of each element of the set modulo $2$, if we use

Full text and comments »

  • Vote: I like it
  • +277
  • Vote: I do not like it

46.
By awoo, history, 5 years ago, translation, In English
Educational Codeforces Round 127 Editorial [problem:1671A] Idea: [user:BledDest,2022-04-23] <spoiler summary="Tutorial"> [tutorial:1671A] </spoiler> <spoiler summary="Solution (BledDest)"> ~~~~~ t = int(input()) for i in range(t): s = input() ans = True n = len(s) for j in range(n): if (j == 0 or s[j] != s[j - 1]) and (j == n - 1 or s[j] != s[j + 1]): ans = False print('YES' if ans else 'NO') ~~~~~ </spoiler> [problem:1671B] Idea: [user:vovuh,2022-04-23] <spoiler summary="Tutorial"> [tutorial:1671B] </spoiler> <spoiler summary="Solution (vovuh)"> ~~~~~ for i in range(int(input())): n = int(input()) x = list(map(int, input().split())) print('YES' if x[-1] - x[0] - n + 1 <= 2 else 'NO') ~~~~~ </spoiler> [problem:1671C] Idea: [user:vovuh,2022-04-23] and [user:BledDest,2022-04-23] <spoiler summary="Tutorial"> [tutorial:1671C] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ fun main() { repeat(rea...
(); modulo[i] = get_modulo(); } }, ++) { c[i] = add(a[i], b[i], modulo[i]); } return c; }, ++) { c[i] = binpow(a[i], b[i], modulo[i]); } return c; }, ++) { c[i] = mul(a[i], b[i], modulo[i]); } return c; }, ++) { c[i] = sub(a[i], b[i], modulo[i]); } return c; }, hs base, modulo;

Full text and comments »

  • Vote: I like it
  • +70
  • Vote: I do not like it

47.
By SanguineChameleon, 19 months ago, In English
Neowise Labs Contest 1 (Codeforces Round 1018, Div. 1 + Div. 2) Editorial [Sorry about problem H.](https://codeforces.me/blog/entry/142069) Thank you for understanding, and we hope you enjoyed the rest of the problems :D --- <h3>[problem:2096A]</h3> Idea: [user:SanguineChameleon,2025-04-20] <br> <spoiler summary="Step 1"> Create your own test cases and solve them! What can you observe? </spoiler> <spoiler summary="Step 2"> What is the length of the $n$-th stick? <spoiler summary="Answer"> - If $s_{n - 1} = \texttt{<}$, then $a_n = 1$, because the $n$-th stick must be shorter than all the other sticks. - If $s_{n - 1} = \texttt{>}$, then $a_n = n$, because the $n$-th stick must be longer than all the other sticks. </spoiler> </spoiler> <spoiler summary="Step 3"> Can we do something similar for the remaining sticks? <spoiler summary="Answer"> Yes! Remove the $n$-th stick, and then solve for the remaining $n - 1$ sticks. We can make similar observations about the $(n - 1)$-th stick. Then, remove the $(n - 1)$-th st...
Because the sum of each column is $0$ modulo $3$, we can uniquely recover any missing element.

Full text and comments »

  • Vote: I like it
  • +242
  • Vote: I do not like it

48.
By peltorator, 5 years ago, In English
Top 10 best Codeforces blog posts of 2021 (in my humble opinion) I really like good blog posts. And that's the main reason I like Codeforces. But as we all know, it's hard to find good blog posts here. So let's help each other and share our favorite posts, which were uploaded to Codeforces in the last year! I will share my top 10, and I encourage you to share some of your favorites in the comments. #### 10. [Heuristic algorithm for Hamiltonian path in directed graphs](https://codeforces.me/blog/entry/90513) by [user:Miracle03,2021-12-24] An absolutely incredible algorithm which kinda sometimes solves the Hamiltonian path problem on some random and special kind of graphs. #### 9. [I compiled a list of almost all useful blogs ever published on Codeforces](https://codeforces.me/blog/entry/91363) by [user:parveen1981,2021-12-24] This blog has a purpose that's similar to the purpose of the blog you're reading right now. A great source of interesting blog posts! #### 8. [Fast modular multiplication](https://codeforces.me/blog/entry/96759...
Some really interesting algorithms that help multiply 64-bit numbers modulo without int128.

Full text and comments »

  • Vote: I like it
  • +210
  • Vote: I do not like it

49.
By Zlobober, 14 years ago, translation, In English
Anti-hash test. Hi everyone! I wan't to share some interesting fact about how we're going to challenge almost every solution, that uses polynomial hashes modulo 2^64. We'll hack any solution, regardless of it's base (!), the only thing we need, that it's using int64 with overflows --- like many coders write hashing. Keywords: Only today, only for you, ladies and gentlemen: we're gonna challenge [user:Petr,2012-07-19]'s solution in problem [problem:7D] from Codeforces Beta Round #7! Is it interesting? Welcome reading after the cut. [cut] Firstly, for the most impatient of you. Here's the source of the generator: ~~~~~ const int Q = 11; const int N = 1 << Q; char S[N]; for (int i = 0; i < N; i++) S[i] = 'A' + __builtin_popcount(i) % 2; // this function in g++ returns // number of ones in binary representation of number i ~~~~~ Let's try solutions of two CFBR #7 winners on this test: Petr Mitrichev's and Vlad Epifanov's. [user:vepifanov,2012-07-18] solution doe...
solution, that uses polynomial hashes modulo 2^64. We'll hack any solution, regardless of it's base, Now the main thing --- this value modulo 2^64 will become zero very-very fast!, So because of that we have such small test length in comparsion with the modulo size 2^64. So

Full text and comments »

  • Vote: I like it
  • +272
  • Vote: I do not like it

50.
By adamant, history, 4 years ago, In English
Nimbers and Sprague-Grundy theorem Hi everyone! Today I'd like to write about the so-called Grundy numbers, or nimbers. I will start by providing a formal recap on the Sprague-Grundy theorem and then will advance to the topic that is rarely covered in competitive programming resources, that is I will write about nimber product and its meaning to the game theory. _I was asked to add the following to the blog: THANK SIR MASTER [user:ADAM_GS,2022-06-12] FOR GREAT AND VALUABLE REVIEW SIR_ ## Prerequisites Familiarity with the following concepts: - Basic [set theory](https://en.wikipedia.org/wiki/Set_theory) notion: [union](https://en.wikipedia.org/wiki/Union_%28set_theory%29), [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) and [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) of sets, [set of all subsets](https://en.wikipedia.org/wiki/Power_set) denoted as $2^A$, etc; - [Groups](https://en.wikipedia.org/wiki/Group_%28mathematics%29) and [fields](https://en.wiki...
Note that $A \oplus A=0$, hence, we may take the number of stones modulo $2$, which results in the

Full text and comments »

  • Vote: I like it
  • +204
  • Vote: I do not like it

51.
By Errichto, 8 years ago, In English
Sums and Expected Value — part 2 ### Instruction I recommend this blog also for red users. Read the theory and problems below, try to solve them. For solutions and extra insight/tips, watch my stream on Monday or watch the video later. If you aren't familiar with EV or summing problems, see part 1 first: [http://codeforces.me/blog/entry/62690] (http://codeforces.me/blog/entry/62690). I will stream a lecture on Monday at [14:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?msg=EV+lecture+2&iso=20181029T14&p1=262) &mdash; [https://www.youtube.com/watch?v=HDk6zQw0Rdo](https://www.youtube.com/watch?v=HDk6zQw0Rdo) (also [Twitch](https://www.twitch.tv/errichto)). I will go through theory and problems from this blog. ### Expected Value theory, part 2 We roll a 6-sided die. Remember, EV of square of the number of pips is something different than square of EV: $$E(X^2) = \frac{1+4+9+16+25+36}{6} = 15.166666\ldots$$ $$E(X)^2 = (\frac{1+2+3+4+5+6}{6})^2 = 3.5^2 = 12.25$$ Two events are ...
answer modulo $10^9+7$.

Full text and comments »

  • Vote: I like it
  • +166
  • Vote: I do not like it

52.
By adamant, history, 5 years ago, In English
Subset convolution interpretation Hi everyone! Recently [user:aryanc403,2021-06-24] [brought up](https://codeforces.me/blog/entry/92128) a topic of subset convolution and some operations related to it. This inspired me to write this blog entry as existing explanations on how it works seemed unintuitive for me. I believe that having viable interpretations of how things work is of extreme importance as it greatly simplifies understanding and allows us to reproduce some results without lust learning them by heart. Also this approach **allows us to easily and intuitively generalize subset convolution** to sum over $i \cup j = k$ _and_ $|i \cap j|=l$, while in competitive programming we usually only do it for $|i \cap j|=0$. Enjoy the reading! <br> [cut] <br> Subset convolution $a \star b$ is defined as follows, let $a=(a_0, ..., a_{2^n-1})$ and $b=(b_0, ..., b_{2^n-1})$. Then \begin{equation} (a \star b)_k = \sum\limits_{i\subset k} a_i b_{k \setminus i} \end{equation} That is, $k$-th term of this con...
We calculate everything modulo $p^2$ and when the division is needed, we just divide it directly, modulo $(x-a_1)\dots(x-a_n)$. Thus if you multiply polynomials component-wise and interpolate them

Full text and comments »

  • Vote: I like it
  • +254
  • Vote: I do not like it

53.
By 4fecta, history, 6 years ago, In English
An Introduction to Plug DP So I realized that there are literally 0 resources written in English on Plug DP, which is one of my favourite DP tricks/techniques that I know of so far. Thus, I hope this serves as a soft introduction for English speakers to this technique, and maybe sheds some light on how powerful it can be. Before we start, I would recommend having a solid understanding of bitmask DP in general in order to get the most out of this blog. Now, let's begin. ### What is Plug DP? In short, Plug DP is a bitmasking technique that allows us to solve complicated problems with relatively simple states and transitions. To illustrate Plug DP in its most primitive form, let's visit a rather classical problem: **How many ways can we fully tile an $N \times M$ grid with $1 \times 2$ dominoes?** This problem can be solved with a standard row-by-row bitmasking approach, but the transitions for that DP state is annoying and unclear at best. Instead, let's investigate an approach that uses a slightly differ...
Here, you can find my implementation for the procedure described above. I take all valuesmodulo

Full text and comments »

  • Vote: I like it
  • +428
  • Vote: I do not like it

54.
By adamant, history, 4 years ago, In English
A bit more of general ideas Hi everyone! Here's another collection of [little tricks](https://codeforces.me/blog/entry/100910) and [general ideas](https://codeforces.me/blog/entry/48417) that might make your life better (or maybe worse). Most of them are somewhat well-known, but perhaps would still be useful to someone. [cut]<hr> 1<!---->. **Evaluating polynomial modulo small prime $p$**. Given a polynomial $q(x)$, it may be evaluated in all possible $a \in \mathbb Z_p$ in $O(p \log p)$. To do this, compute $q(0)$ separately and use [chirp Z-transform](https://codeforces.me/blog/entry/83532) to compute $q(g^0), q(g^1), \dots, q(g^{p-2})$, where $g$ is a primitive root modulo $p$. _This method can be used to solve [problem:1054H]._ 2<!---->. **Generalized Euler theorem**. Let $a$ be a number, not necessarily co-prime with $m$, and $k > \log_2 m$. Then $$ a^k \equiv a^{\phi(m) + k \mod \phi(m)} \pmod m, $$ where $\phi(m)$ is Euler's totient. This follows from the Chinese remainder theor...
// multiply a+bx and c+dx modulo x^2 = y lin operator * (const lin& t) { return lin, 1. **Evaluating polynomial modulo small prime $p$**. Given a polynomial $q(x)$, it may be, modulo $b_i$, after which the maximum is taken on contiguous segments of the same width rather than with

Full text and comments »

  • Vote: I like it
  • +214
  • Vote: I do not like it

55.
By ouuan, history, 7 years ago, In English
Codeforces Round #564 Editorial [problem:1173A] Idea: [user:ouuan,2019-06-07] <spoiler summary="Tutorial"> Consider the two edge cases: all the $z$ persons upvote / all the $z$ persons downvote. If the results are the same in these two cases, it is the answer. Otherwise, the result is uncertain. </spoiler> <spoiler summary="Solution"> ```cpp #include <iostream> using namespace std; const char result[4] = {'+', '-', '0', '?'}; int solve(int x, int y) { return x == y ? 2 : x < y; } int main() { int x, y, z; cin >> x >> y >> z; cout << result[solve(x + z, y) == solve(x, y + z) ? solve(x, y) : 3]; return 0; } ``` </spoiler> [problem:1173B] Idea: [user:Sooke,2019-06-07] <spoiler summary="Tutorial"> - $m\ge\left\lfloor\frac n 2\right\rfloor+1$ Consider the chess pieces $1$ and $n$. $\because\begin{cases}|r_1-r_n|+|c_1-c_n|\ge n-1\\\\|r_1-r_n|\le m-1\\\\|c_1-c_n|\le m-1\end{cases}$ $\therefore m-1+m-1\ge n-1$ $\therefore m\ge\frac{n+1}2$ $\because m\...
Last question: how to calculate the result modulo $998244353$?

Full text and comments »

  • Vote: I like it
  • +219
  • Vote: I do not like it

56.
By neal, 6 years ago, In English
Unofficial Editorial for Educational Round 95 (Div. 2) Here are my approaches to the problems today: #### [problem:1418A] Since the second trade is the only way to get coal, we clearly need to perform the second trade $k$ times. So how many times do we need to do the first trade? We can see that in order to end up with enough sticks and coal by the end, we need to obtain $ky + k$ sticks ($ky$ to convert to coal and $k$ to save as sticks). Since the first trade really just gives us $x - 1$ new sticks each time, we'll need to make $\displaystyle \left \lceil \frac{ky + k - 1}{x - 1} \right \rceil$ first trades ([reference to floor and ceiling functions](https://en.wikipedia.org/wiki/Floor_and_ceiling_functions) for anyone unfamiliar). For implementation details, note that for positive integers $a$ and $b$, $\displaystyle \left \lceil \frac{a}{b} \right \rceil = \left \lfloor \frac{a + b - 1}{b} \right \rfloor$. Code: [submission:92851684] #### [problem:1418B] We can think about the problem as follows: we want to order the $a_i$ to...
array, modulo 3. So if the prefix is [3, 2, 1, 2, 2], our signature should be [1, 0, 1], since 1

Full text and comments »

  • Vote: I like it
  • +368
  • Vote: I do not like it

57.
By tibinyte2006, 4 years ago, In English
CodeTON Round 3 (Div. 1 + Div. 2) Editorial [A — Indirect Sort](https://codeforces.me/contest/1750/problem/A) ===== Authors: [user:mejiamejia,2022-10-31], [user:Ecrade_,2022-11-06] <spoiler summary="Solution"> We claim that we can sort the array if and only if $a_1 = 1$. **Necessity** We can notice that index $1$ cannot be affected by any swap operation. Let's see what happens to the value $1$. According to the definition of the operation, it can either increase or be swapped. In order to be increased, there must exist some $k$ such that $1 > a_k$, but since $1$ is the minimum possible value, it will never be true as other values in array $a$ can only increse as well. Since index $1$ can not be affected by a swap operation and $a_1>1$, we conclude that if $a_1 \neq 1$, the answer is **No**. **Sufficiency** Let's focus on the second operation. Since we have $a_1 = 1$, we can always choose $i=1$ and the operation then turns into picking some pair $2 \le j < k \le n$ and swapping $a_j$ with $a_k$. It's t...
**Challenge: Solve the problem in $O(nlog^2)$ or $O(nlog)$ ( modulo is prime )**

Full text and comments »

  • Vote: I like it
  • +253
  • Vote: I do not like it

58.
By adamant, history, 4 years ago, In English
Integer solutions to x² + y² = z Hi everyone! As I continue working through Project Euler, I want to write a blog about another piece of general mathematical knowledge that is both interesting on its own and might be useful in some problems. Consider the following Diophantine equation: $$ x^2 + y^2 = z. $$ We assume that we're given a specific number $z \in \mathbb Z$, and we need to check if there are $x, y \in \mathbb Z$ for which the identity above holds. Then, if such numbers exist we should find them and report. Example of a problem that might need it: **[Timus &mdash; 1593. Square Country. Version 2](https://acm.timus.ru/problem.aspx?space=1&num=1593)**. You're given an integer $n$. Find minimum $k$ such that $n = a_1^2+\dots+a_k^2$. #### Tl;dr. Let $z = 2^{k_0} p_1^{k_1} \dots p_n^{k_n} p_{n+1}^{k_{n+1}} \dots p_m^{k_m}$, where $p_1, \dots, p_n$ are different prime numbers with remainder $3$ modulo $4$, and $p_{n+1}, \dots, p_m$ are different prime numbers with remainder $1$ modulo $4$. Then the...
))$, where $d_k(z)$ is the number of divisors of $z$ that have remainder $k$ modulo $4$., - $a=0$ or $b=0$ and the non-zero number is prime with remainder $3$ modulo $4$, - $a^2 + b^2$ is, . What's good about prime numbers is that remainders modulo prime numbers form a field (i.e. they work, modulo $z$ on both parts: $$ x^2+y^2 \equiv 0 \pmod z. $$ This relaxed version is equivalent to

Full text and comments »

  • Vote: I like it
  • +134
  • Vote: I do not like it

59.
By adamant, history, 5 years ago, In English
Recovering a linear recurrence with the extended Euclidean algorithm Hi everyone! The task of finding the minimum linear recurrence for the given starting sequence is typically solved with the Berlekamp-Massey algorithm. In this article I would like to highlight another possible approach, with the use of the extended Euclidean algorithm. Great thanks to [user:nor,2022-04-08] for the proofreading and all the useful comments to make the article more accessible and rigorous. ### Tl'dr. The procedure below is essentially a formalization of the extended Euclidean algorithm done on <!--$a$-->$F(x)$ and $x^{m+1}$. If you need to find the minimum linear recurrence for a given sequence $F_0, F_1, \dots, F_m$, do the following: Let $F(x) = F_m + F_{m-1} x + \dots + F_0 x^m$ be the generating function of the reversed $F$. Compute the sequence of remainders $r_{-2}, r_{-1}, r_0, \dots, r_k$ such that $r_{-2} = F(x)$, $r_{-1}=x^{m+1}$ and $$r_{k} = r_{k-2} \mod r_{k-1}.$$ Let $a_k(x)$ be a polynomial such that $r_k = r_{k-2} - a_k r_{k-1}$. ...
Assuming $\deg f(x) \leq p+q$ (otherwise we can take it modulo $x, /inv_of_polynomials)**. You're given $f(x)$ and $h(x)$. Compute $f^{-1}(x)$ modulo $h(x)$.

Full text and comments »

  • Vote: I like it
  • +175
  • Vote: I do not like it

60.
By orz, history, 5 years ago, translation, In English
Fast modular multiplication Consider the following problem: given three integers $x$, $y$ и $m$, $0 \leqslant x,y < m < 2^{32}$, calculate $xy\bmod m$. The easy way is just to multiply these numbers and apply the modulo operation: ~~~~~ uint32_t prod(const uint32_t x, const uint32_t y, const uint32_t m) { return x * y % m; } ~~~~~ As you might have guessed, this solution is wrong. The thing is that an overflow is possible in such a procedure: the operation `x * y` is performed in the type` uint32_t`, and in fact the intermediate result of this operation will not be $xy$, but $xy\bmod2^{32}$. If after that we take the result modulo $m$, it may differ from the correct one: $$ \left(xy\bmod2^{32}\right)\bmod m\ne xy\bmod m. $$ The way out is simple — you need to multiply in a larger type: ~~~~~ uint64_t prod_uint64(const uint64_t x, const uint64_t y, const uint64_t m) { return x * y % m; } ~~~~~ If you do this, then, since $xy<2^{64}$, this product will definitely not overflow, and after tak...
calculates the product modulo, provided that `uint64_t c = (double) x * y / m` was calculated absolutely, the result modulo $m$, it may differ from the correct one: $$ \left(xy\bmod2^{32}\right)\bmod m\ne, , and after taking the result modulo, you will get the correct answer., }$, calculate $xy\bmod m$. The easy way is just to multiply these numbers and apply themodulo

Full text and comments »

  • Vote: I like it
  • +269
  • Vote: I do not like it

61.
By Endagorion, 12 years ago, In English
Codeforces Round #295 Editorial (now with bonuses!) We would like to thank the testers of this round's and Winter Computer Camp olympiad's problems: [user:alger95,2015-03-02], [user:thefacetakt,2015-03-02], [user:adamant,2015-03-02], [user:dragonic,2015-03-02], [user:Who179,2015-03-02], [user:ASverdlov,2015-03-02]. Make sure to comment if you find any mistakes. **UPD**: I've just remembered to put up the usual challenges for the problems. So, here they go. [problem:520A] Idea: [user:Endagorion,2015-03-02] Preparation: [user:Endagorion,2015-03-02] To check that every letter is present in the string we can just make a boolean array of size 26 and for every letter set the corresponding variable to TRUE. In the end check that there are 26 TRUEs. That is an $O(n)$ solution. Also don't forget to change all letters to lowercase (or all to uppercase). To make all the letters lowercase, one could use standard functions, like `tolower` in Python. Also, it is known that the letters from `a` to `z` have consecutive ASCII numbe...
capitalization of some letters are considered distinct. Can you find the answer modulo some prime $p$ in linear, the number of disjoint unions of _cacti_.) Find the answer modulo $10^9 + 7$. Can you come up with any, (n \log n \log k)$ solution? Maybe even better? (Hint: the modulo should be an _appropriately chosen_, To compute these sums, we will need to know all powers of 10 up to $n$-th ( modulo $10^9 + 7

Full text and comments »

  • Vote: I like it
  • +151
  • Vote: I do not like it

62.
By adamant, history, 4 years ago, In English
Partitions and pentagonal number theorem Hi everyone! In today's blog I'd like to write about the theorem that allows to efficiently solve the following problems: - What is the number of partitions of a non-negative number $n$ for $n \leq 10^5$? - What is the number of partitions of a non-negative number $n$ for $n \leq 10^5$, so that no summand repeats $d$ or more times? - What is the number of partitions of a non-negative number $n$ for $n \leq 10^5$, so that no summand is divisible by $d$? - **[HackerEarth &mdash; Perfect Permutations](https://www.hackerearth.com/de/problem/algorithm/perfect-permutations-september-clash/)**: What is the number of permutations of length $n$ with $k$ inversions for $k \leq n \leq 10^5$? - **[problem:102354E]**: Let $\phi = \frac{9}{10} \cdot \frac{99}{100} \cdot \frac{999}{1000} \cdot \dots$, what is the $k$-th digit of $\phi$ for $k \leq 10^{18}$? - **[SNSS-2018 Round 5 &mdash; Investment Portfolio](https://contest.yandex.ru/contest/8703/problems/C/)**: You have $2n$ dollars and ...
Let's take the logarithm of the RHS taken modulo $x^{n+1}$:

Full text and comments »

  • Vote: I like it
  • +172
  • Vote: I do not like it

63.
By Errichto, 7 years ago, In English
My Coding Streams in May&June You can watch me on https://www.twitch.tv/errichto or https://www.youtube.com/errichto2. There is schedule with countdown on Twitch. Most likely I will stream in May on Tuesday mornings and Sunday evenings. - [May 3, 16:45 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?iso=20200503T1645&p1=262) &mdash; **Codeforces hard** (solving hard problems because the round was moved) - [May 5, 9:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?iso=20200505T09&p1=262) &mdash; **Boring Programming Stream** (planning videos, fixing chatbot, maybe learning Berlekamp–Massey) - [May 10, 18:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?iso=20200510T18&p1=262) &mdash; **Atcoder hard** (Grand Contest 43?) - [May 12, 9:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?iso=20200512T09&p1=262) &mdash; **Atcoder hard** or something similar to practice for Google Code Jam. - [May 17, 18:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.htm...
two recent videos for beginners: Computations Modulo P, Binary Exponentiation in works: Matrix

Full text and comments »

  • Vote: I like it
  • +168
  • Vote: I do not like it

64.
By fchirica, 13 years ago, In English
Codeforces Round #225 — Editorial [problem:384A] ================== Usually, when you don’t have any idea how to approach a problem, a good try is to take some small examples. So let’s see how it looks for N = 1, 2, 3, 4 and 5. With C I noted the coder and with * I noted an empty cell. ![ ](http://s28.postimg.org/8z1d7k399/New_Bitmap_Image.png) By now you should note that answer is N ^ 2 / 2 when N is even and (N ^ 2 + 1) / 2 when N is odd. Good. Generally, after you find a possible solution by taking examples, you need to prove it, then you can code it. In order to proof it, one needs to do following steps: 1/ prove you can always build a solution having N ^ 2 / 2 (or (N ^ 2 + 1) / 2) pieces. 2/ prove that N ^ 2 / 2 (or (N ^ 2 + 1) / 2) is maximal number – no other bigger solution can be obtained. For proof 1/ imagine you do coloring like in a chess table. ![ ](http://s27.postimg.org/ysqhphx0z/New_Bitmap_Image.png) The key observation is that by placing all coders on black squares of tab...
modulo 2. All nodes having remainder L modulo 2 will be added a +val, and nodes having reminder (L + 1

Full text and comments »

  • Vote: I like it
  • +418
  • Vote: I do not like it

65.
By sum, history, 3 years ago, In English
Editorial for Codeforces Round #919 (Div. 2) ##Information about the round <spoiler summary="Rating predictions (inspired by BucketPotato's editorial)"> | Person | A | B | C | D | E | F1 | F2 | |--------------------------------------------|------|------|------|------|------|------|------| | [user:sum,2024-01-13] | 800 | 1300 | 1500 | 1900 | 2000 | 2200 | 2900 | | [user:oursaco,2024-01-13] | 800 | 1100 | 1300 | 1600 | 1800 | 2100 | 3100 | | [user:omeganot,2024-01-13] | 900 | 1000 | 1400 | 1700 | 1900 | 2200 | 2800 | | [user:sriniv,2024-01-13] | | | | 1900 | 2000 | 1900 | | | [user:apple_method,2024-01-13] | 1000 | 1200 | 1400 | 1900 | 1600 | | | | [user:awesomeguy856,2024-01-13] | 800 | 1100 | 1400 | 1800 | 1900 | 2000 | 2800 | | [user:nonrice,2024-01-13] | 900 | 1000 | 1400 | 1750 | | | | | [user:null_aw...
$m$ are they equal (modulo $m$)? , factor of $|x-y|$, then $x$ and $y$ will be equal modulo $m$.

Full text and comments »

  • Vote: I like it
  • +314
  • Vote: I do not like it

66.
By errorgorn, 5 years ago, In English
Linear Basis (Xor Basis Extended) As part of the graduation requirements for my school, I have to complete a simple research project, so I decided to do something related to data structure and algorithms. I believe I have come out with a data structure that maintains the basis of vectors in $(\mathbb{Z}/m\mathbb{Z})^d$, where $m$ **may not be prime**. Since this was related to competitive programming, I think it is a good idea to share it here. Hopefully, this algorithm is actually novel :P I would like to thank: - [user:icypiggy,2021-12-26] for being my research mentor and tolerating my dumb questions - [user:rama_pang,2021-12-26] and [user:adamant,2021-12-28] for their helpful suggestions and comments Please comment under the blog or message me on codeforces if any parts are unclear or wrong. Also, I hope that some LGMs can help solve the open problems in this blog. # Introduction Maintaining the basis of vectors in $(\mathbb{Z}/2 \mathbb{Z})^d$, also known as the xor basis algorithm is a well-studie...
Note that in the above $2$ algorithms, we are doing all operations modulo $m$ with the exception of

Full text and comments »

  • Vote: I like it
  • +381
  • Vote: I do not like it

67.
By adamant, 10 years ago, translation, In English
General ideas **// Finally translated!** Hi everyone! Do you like ad hoc problems? I do hate them! That's why I decided to make a list of ideas and tricks which can be useful in mane cases. Enjoy and add more if I missed something. :) [cut]<br> **1. Merging many sets in $O(n\log{n})$ amortized.** If you have some sets and you often need to merge some of theme, you can do it in naive way but in such manner that you always move elements from the smaller one to the larger. Thus every element will be moved only $O(\log{n})$ times since its new set always will be at least twice as large as the old one. Some versions of DSU are based on this trick. Also you can use this trick when you merge sets of vertices in subtrees while having dfs. **2. Tricks in statements, part 1.** As you may know, authors can try to hide some special properties of input to make problem less obvious. Once I saw constraints like $\relax 1 \leq a \leq b \leq 10^5, \dots, ab \leq 10^5$. Ha-ha, nice joke. It is actually...
over field $\relax Z_2$ of residues modulo 2. This interpretation useful because ordinary methods of, **17. Modulo product of two polynomials with real-valued FFT.** If mod is huge we can lack accuracy

Full text and comments »

  • Vote: I like it
  • +296
  • Vote: I do not like it

68.
By LucaLucaM, history, 14 months ago, In English
Codeforces Round 1051 (Div. 2) Editorial Thanks everybody for participating in the round! [problem:2143A] Author: [user:LucaLucaM,2025-09-17], Preparation: [user:LucaLucaM,2025-09-17], Editorial: [user:MateiKing80,2025-09-17] <spoiler summary="Solution"> [tutorial:2143A] </spoiler> <spoiler summary="Code"> ``` #include <iostream> #include <cassert> #include <vector> #include <algorithm> #define debug(x) #x << " = " << x << '\n' using ll = long long; #define YES std::cout << "YES" << std::endl; #define NO std::cout << "NO" << std::endl; void solve() { int n; std::cin >> n; std::vector<int> p(n); for (int i = 0; i < n; i++) { std::cin >> p[i]; } int l = 0, r = n - 1; for (int i = 1; i <= n; i++) { if (p[l] == i) { l++; } else if (p[r] == i) { r--; } else { NO; return; } } YES; } int main() { int t; std::cin >> t; for (int tc = 1; tc <= t; tc++) { solve(); } return 0; } ``` </sp...
const int NMAX = 3000; const int modulo = 1e9 + 7;, void addSelf(int &x, int y) { x += y; if (x >= modulo) x -= modulo; }

Full text and comments »

  • Vote: I like it
  • +166
  • Vote: I do not like it

69.
By AquaMoon, 3 years ago, In English
Harbour.Space Scholarship Contest 2023-2024 (Div. 1 + Div. 2) Editorial Thank you for participation and we hope you enjoy this round ヽ(^ o ^)/. During the contest, there was a small issue in problem D. For those affected, we have skipped your duplicate submissions (if your duplicate submissions were not skipped, please let us know). We apologize again for any inconvenience caused. In addition, we are honored to invite you to our unofficial round tomorrow (*╹▽╹*) [Invitation to TheForces Round #22 (Interesting-Forces)](https://mirror.codeforces.com/blog/entry/119771) ### [1864A-Increasing and Decreasing](https://mirror.codeforces.com/contest/1864/problem/A) Idea : [user:wuhudsm,2023-08-27] <spoiler summary="Tutorial"> We use the following greedy construction: For all $i$ ($1<i<n$), set $a_i=a_{i+1}-(n-i)$. If $a_2-a_1 \geq n-1$, we've found a solution, otherwise there is no solution. Proof. Assume there's a solution which includes an index $i$ ($1<i<n$) such that $a_{i+1}-a_i>n-i$. We can make $a_j:=a_j+\Delta$ for all $j$ ($2 \le j ...
values of the indices modulo $2$. For example, if $n$ is $10$, the indices modulo $2$ are, We can find out that after reversing any subarray of length $k$, the indices modulo $2$ do not

Full text and comments »

  • Vote: I like it
  • +201
  • Vote: I do not like it

70.
By Xiaohuba, 13 months ago, In English
Codeforces Global Round 30 Editorial ## A Sequence Game Idea from [user:cmk666,2025-11-06], Prepared by [user:cmk666,2025-11-06] <spoiler summary="Hint 1"> Think some straightforward necessary conditions. They are also sufficient. </spoiler> <spoiler summary="Tutorial"> [tutorial:2164A] </spoiler> ## B Even Modulo Pair Idea from [user:244mhq,2025-11-06], Prepared by [user:NetSpeed1,2025-11-06] <spoiler summary="Hint 1"> Consider a brute force solution. What's the actual complexity of it? </spoiler> <spoiler summary="Tutorial"> [tutorial:2164B] </spoiler> ## C Dungeon Idea from [user:Link_Cut_qwq,2025-11-06], Prepared by [user:Xiaohuba,2025-11-06] <spoiler summary="Hint 1"> If you gain a new sword after killing a monster, its damage will be greater or equal than the previous sword. </spoiler> <spoiler summary="Hint 2"> When will we attempt to kill monsters with $c_i = 0$? </spoiler> <spoiler summary="Hint 3"> Consider a greedy approach. </spoiler> <spoiler summ...
## B Even Modulo Pair

Full text and comments »

  • Vote: I like it
  • +176
  • Vote: I do not like it

71.
By purplesyringa, history, 3 years ago, In English
FFT is less precise than you think TL;DR: the popular empirical bounds for FFT stability overestimate the precision by a few bits -- multiplication might thus produce wrong answer even after thorough testing on random inputs. ## Introduction So here's how people typically advise you to use FFT after proving various theorems and providing a $\mathcal{O}(n \log n)$ algorithm. Suppose you want to multiply two big integers, stored in binary. Split them into groups of $B$ bits, called $a_0, a_1, \dots$ and $b_0, b_1, \dots$ respectively, so that the integers are equal to $a_0 + a_1 x + \dots$, $b_0 + b_1 x + \dots$ for $x = 2^B$. Multiply the polynomials $(a_0 + a_1 x + \dots) (b_0 + b_1 x + \dots)$ via FFT and substitute $x = 2^B$ to obtain the $n$-bit product. $B$ is a variable here -- the algorithm works for every $B$, but larger $B$s are faster. We're limited by precision of `double` though, because `double` can only precisely store integers from $0$ to $2^{53} \approx 9 \cdot 10^{15}$ (e.g. $2^{53}+1$ cann...
$ and check if $P(x_0) \cdot Q(x_0)$ equals $R(x_0)$ (modulo $M$). $M$ doesn't necessarily have to, > Colin Percival, Rapid multiplication modulo the sum and difference of highly composite numbers

Full text and comments »

  • Vote: I like it
  • +217
  • Vote: I do not like it

72.
By dmkozyrev, history, 8 years ago, translation, In English
[Tutorial] Rolling hash and 8 interesting problems [Editorial] **UPD**: while I was translating this post from Russian to English, [user:dacin21,2018-07-06] wrote his post, more advanced, [link](http://codeforces.me/blog/entry/60442). I hope that my post will help beginners, but in my post more rough estimates. And in Russia we call **rolling hashes** as a **polynomial hashes**. Hello, codeforces! This blogpost is written for all those who want to understand and use polynomial hashes and learn how to apply them in solving various problems. I will briefly write the theoretical material, consider the features of the implementation and consider some problems, among them: 1. Searching all occurrences of one string of length $n$ in another string length $m$ in $O(n + m)$ time 2. Searching for the largest common substring of two strings of lengths $ n $ and $ m $ $(n \ge m) $ in $O((n+m \cdot log(n)) \cdot log(m))$ and $O(n \cdot log(m))$ time 3. Finding the lexicographically minimal cyclic shift of a string of length $ n $ in $ O(n \cdo...
taken modulo $m$. Then:, $, then the ring of residues modulo $m = m_1 \cdot m_2$ is equivalent to the product of ringsmodulo $m_1, For taking remainder from division by modulo $2^31-1 = 2147483647$ for **positive** $x$ not greater, If we take a prime modulo of the order $10^9$, then we will not go through any of the maximum tests., In the case of addition and subtraction modulo $m_1$ of two remainders, we can use ternary operator, One such comparison can be performed in $O(1)$ time, assuming the degree of $p$ modulo

Full text and comments »

  • Vote: I like it
  • +239
  • Vote: I do not like it

73.
By Everule, history, 5 years ago, In English
Essentials of Elementary Number Theory This is a blog starting from the very basics of number theory, in a way that flows fluidly from one concept to another and is based in developing an intuitive feeling for the basics of elementary number theory. This is not a blog to simply gloss over. I consider more of a guided exploration into the world of discovering things in the world of number theory, and I don't expect anyone to immediately understand all the insights in this blog. But if you put an honest effort into discovering how I find these insights you will find much use for my blog. If you do not know some notation or some elementary theorem I use you should refer to this. <spoiler summary="Elementary definitions"> We start with the basic definition that is at the heart of number theory. Let $a \mid b$ (read a divide(s) b) for some $a,b \in \mathbb{Z}$ for some if there exists $k \in \mathbb{Z}$ such that $b = ak$. Similarly $a \not\mid b$ if there does not exist such $k$. If $g \mid a$, then $g \mid ab$. ...
can be solved by Bezout's Theorem if $\gcd(n_1, n_2) \mid a_2 - a_1$. Essentiallymodulo the common

Full text and comments »

  • Vote: I like it
  • +308
  • Vote: I do not like it

74.
By Qwerty1232, 19 months ago, In English
Making NTT convolution 10x faster with avx2 > Text is also available on [github pages](https://piskareviv.github.io/blog_aux_ntt_1/) (formatting may look a bit cleaner there) > Thanks [user:alexxela12345,2025-05-05] for reviewing this blog Hello everyone! I want to share some of my thoughts and experiments on vectorizing NTT. I prefer NTT to real-valued FFT because of the imprecision of the latter. I use `avx2` because it is the most advanced vector extension supported by the majority of modern online judges (including Codeforces), as of 2024. And I have no idea how many bugs (already found two) and how much UB my code contains, at least it passes some kind of tests. ### Benchmark info All the benchmarks are performed on my `Ubuntu 22` `Intel i5-1135g7` laptop. I execute `cpupower frequency-set -d 3.0ghz -u 3.0ghz` before benchmarks to (attempt to) fix CPU frequency for better accuracy. Code is available at [github](https://github.com/piskareviv/blog_aux_ntt_1). You can try running all the benchmarks o...
inverse modulo $2^{32}$, we can use Newton's method instead (what we need is exactly the 2-adic, ) \bmod (x^8 - w_i)$ modulo $(x^8 - w_i)$ straight away., **There is a problem**: $r$ is not congruent to $x$ modulo $\text{mod}$, it is congruent to $x

Full text and comments »

  • Vote: I like it
  • +366
  • Vote: I do not like it

75.
By adamant, history, 5 years ago, In English
Lagrange interpolation and partial fraction decomposition Hi everyone! Today I'd like to write yet another blog about polynomials. Specifically, I will cover the relationship between polynomial interpolation and Chinese remainder theorem, and I will also highlight how it is useful when one needs an explicit meaningful solution for partial fraction decomposition. [cut]<br> #### Lagrange interpolation It's quite well-known that the system $$\begin{cases}P(x_0) = y_0, \\ P(x_1) = y_1, \\ \dots \\ P(x_n) = y_n\end{cases}$$ has a unique solution $P(x)$ among polynomials of degree at most $n$. A direct way to prove that $P(x)$ exists is through Lagrange's interpolation. To have a better grasp of it, let's recall that $P(x) \equiv P(x_0) \pmod{x-x_0}$, thus system becomes $$\begin{cases}P(x) \equiv y_0 \pmod{x-x_0}, \\ P(x) \equiv y_1 \pmod{x-x_1}, \\ \dots \\ P(x) \equiv y_n \pmod{x-x_n}.\end{cases}$$ From the Chinese remainder theorem follows that $P(x)$ is unique modulo $Q(x) = (x-x_0)\dots(x-x_n)$ and is explicitly given ...
For $d_i=1$ we knew that $Q^{-1}(x)$ modulo $x-x_i$ is equial to the inverse of $Q(x_i)$. To, From the Chinese remainder theorem follows that $P(x)$ is unique modulo $Q(x) = (x-x_0)\dots(x-x_n, So, equivalence modulo the polynomial which have multiple roots is, essentially, still equivalent

Full text and comments »

  • Vote: I like it
  • +171
  • Vote: I do not like it

76.
By adamant, history, 3 years ago, In English
Useful substitutions with generating functions Hi everyone! Today I would like to write about some identities that might come handy when using generating functions to solve competitive programming problems. I will also try to include some useful examples about them. #### Some notation For brevity, we will sometimes skip the specific bounds in indexed sums, meaning that the summation happens among all _valid_ indices. Please also read the information below if you're not familiar with generating functions, or want to brush up on some aspects. <spoiler summary="Definitions and notation"> Let's briefly recall that, for a sequence $a_0, a_1, \dots$, it's **ordinary generating function** (OGF) is defined as a formal power series $$ F(x) = \sum\limits_k a_k x^k, $$ and its **exponential generating function** (EGF) is defined as $$ F(x) = \sum\limits_k a_k \frac{x^k}{k!}. $$ Generating functions are used because it's very simple to represent convolutions with them. For two sequences $a_0, a_1, \dots$ and $b_...
$$ \frac{1- f_m (1+t)^m - f_{m-1} (1+t)^{m+1}}{1-(1+t)-(1+t)^2} $$ truncated modulo $t^{k+1}$. It

Full text and comments »

  • Vote: I like it
  • +182
  • Vote: I do not like it

77.
By Endagorion, 12 years ago, In English
Codeforces Round #265 Editorial I'll upload my example solutions and will post links to them as soon as it becomes possible. Some of the problems editorials contain an additional challenge which is apparently harder to comprehend than the original problem. Feel free to share and discuss your ideas in the comments. =) [problem:465A] If we add 1 to a number, its binary representation changes in a simple way: all the least significant $1$'s change to $0$'s, and the single following $0$ changes to $1$. It suffices to find the length of largest suffix which contains only $1$'s, suppose its length is $l$. Then the answer is $l+1$ except for the case when all the string consists of $1$, when the answer is $l$. It is amusing that div1E problem is concerned with addition of 1 to a binary integer as well. =) [problem:465B] Optimal strategy is as follows: for every segment of consecutive $1$'s open the first letter in segment, scroll until the last letter in segment, if there are more unread letters left, retu...
})$ and $s_d = 10^{|t_{d}|}$ for all $d$. As we need answer modulo $P=10^9+7$ we can store these numbers

Full text and comments »

  • Vote: I like it
  • +172
  • Vote: I do not like it

78.
By adamant, history, 3 years ago, In English
Dirichlet convolution. Part 2: Dirichlet series and prime counting Hi everyone! Recently I've published a [blog](https://codeforces.me/blog/entry/117635) about how one can multiply and divide sequences with Dirichlet convolution. In this blog, we will learn about a convenient framework to reason about them in a "coordinate-free" notation, similar to how generating functions are used to analyze sequences under the regular convolution. - **[Part 1: Fast prefix sum computation](https://codeforces.me/blog/entry/117635)** - **Part 2: Dirichlet series and prime counting** We will learn how to deal with Dirichlet multiplication and division in the framework of Dirichlet series, and derive a number of well known number theoretic results from this perspective. While doing so, we will learn about Riemann zeta function and will have a glimpse into why it is so important in analyzing behavior of prime numbers. We will also learn how Dirichlet series framework helps us to, given $g(1), \dots, g(n)$, to compute $f(1), \dots, f(n)$ in $O(n \log n)$ s...
modulo } p \text{ and } a \not\equiv 0\pmod p, \\ -1 & \text{if } a \text{ is a quadratic nonresidue

Full text and comments »

  • Vote: I like it
  • +113
  • Vote: I do not like it

79.
By AlexLuchianov, 5 years ago, In English
[Tutorial] Sparse table The most common example when talking about sparse tables is the following problem: _"Given an array of $N$ integers, your task is to process $Q$ queries of the form: what is the minimum value in range $[a,b]$?"_ A brute-force approach would be to iterate over all of the elements of each query interval. This approach has $O(NQ)$ time complexity and is quite slow. One way to improve the time complexity would be to precompute the minimum value for various intervals and then use this information to speed up the queries. For what intervals should we precompute the minimum value? For a start, let's try precomputing it for all intervals of length $2$, $4$, $8$ and so on. More formally, let $rmq[h][i]$ be the minimum value on the interval $[i, i + 2^h - 1]$. One simple and efficient way to precompute this table is by observing that one interval whose length is a power of $2$ can be split into $2$ smaller intervals. This observation translates into the following recurrence relation:...
_Count the number of strings respecting all the $M$ restrictions. Print your answermodulo $10^9+7$."_

Full text and comments »

  • Vote: I like it
  • +195
  • Vote: I do not like it

80.
By peltorator, 6 years ago, translation, In English
Video: Segment Tree Beats Hi! In the new video, we’re going to talk about the amazing data structure called Segment Tree Beats, which allows us to support a huge number of operations that a regular segment tree can’t handle. We will learn how to take numbers on a segment modulo some number, apply the min= and max= operations, add += to them, and also find GCD on a segment with these operations. And all the proofs are gonna be super simple, so don’t be scared, it will be easy! In the next video, we will cover even more awesome queries, so stay tuned. [Link to the video](https://youtu.be/NwkO73jGSPA) You can check out my previous videos on [my channel](https://www.youtube.com/c/peltorator) Contest on Segment Tree Beats (and others) is [here](https://codeforces.me/group/1rv4rhCsHp/contests) Also, there's the Russian version of this video if you speak Russian [here](https://youtu.be/58csqxAD8vM) ![ ](/predownloaded/47/25/47253e8a4d9533f695452d8c4b52b0332ca5e4bb.png) [Original article in En...
will learn how to take numbers on a segment modulo some number, apply the min= and max= operations

Full text and comments »

  • Vote: I like it
  • +374
  • Vote: I do not like it

81.
By henotrix, 15 months ago, In English
Codeforces Round 1045 (Div. 2) Editorial Unfortunately, the round turns out to be very unbalanced :( I'm deeply sorry about this issue. I hope you still enjoy the problems. <spoiler summary="Rate the contest! (definitely not copied from past contests)"> <spoiler summary="Quality"> * Excellent contest * Good contest * Average contest * Bad contest * Horrible contest </spoiler> <spoiler summary="Difficulty"> * Trivial contest * Easy contest * Average contest * Hard contest * Impossible contest </spoiler> </spoiler> [problem:2134A] <spoiler summary="Hint 1"> Check the parity of numbers $a$, $b$, and $n$. </spoiler> <spoiler summary="Solution"> Let us first consider the $b$ blue cells. Since all $b$ cells appear in the final painting, for the coloring to be symmetric, they must be placed at the middle of the grid...
where $k^{-1}$ is the modular inverse of $k$ modulo $g$.

Full text and comments »

  • Vote: I like it
  • +199
  • Vote: I do not like it

82.
By Siyah, history, 12 months ago, In English
Kitamasa Method! ### From Matrix Exponentiation to Kitamasa Method --- Hi, I'm AmirMohammad (commonly known as Danet). Naturally, as a non-native speaker, the translation and editing process involved some assistance. If you spot any technical or linguistic errors, I would be grateful if you pointed them out! **Faster Computation of Linear Recurrence DP** ### Problem Statement We are given a linear recurrence relation of order \( k \): $$ \begin{align} dp[n] &= c_1 \cdot dp[n-1] + c_2 \cdot dp[n-2] + \dots + c_k \cdot dp[n-k] \end{align} $$ Along with the first \( k \) values: $$ \begin{align} dp[0],\ dp[1],\ \dots,\ dp[k-1] \end{align} $$ Our goal is to compute \( dp[n] \) efficiently for very large \( n \). ## Classical Solution: Matrix Exponentiation **State Definition** To compute the recurrence, we always need the last \( k \) values. So we define the state vector as: $$ \begin{align} V(i) &= [\, dp[i],\ dp[i-1],\ dp[i-2],\ \dots,\ dp[i-k+1] \,] \end...
Steps: 1. Multiply two polynomials of degree \( < k \) 2. Reduce the result modulo p(x)., Taking modulo \( p(x) \):

Full text and comments »

  • Vote: I like it
  • +249
  • Vote: I do not like it

83.
By adamant, history, 3 years ago, In English
Efficient linear algebra for dummies Hi everyone! Some time ago I started developing a linear algebra library for Library Checker, and it turned out to be much fun. I'd like to write this blog to outline how one can implement a linalg library with a very good Library Checker performance, while also avoiding highly technical low-level details that are common in other similar blogs. Instead, we will learn a few high level ideas that will let us write a code that the compiler will then optimize using all these fancy techniques _in our stead_. Huge thanks to ~ToxicPie9,2024-05-08 and [user:magnus.hegdahl,2024-05-08] for explaining me some of the optimizations used here! You may also look into ~sslotin,2024-05-08's [entry](https://codeforces.me/blog/entry/101655) about how it can be sped up even further with more advanced and low-level techniques. ### Tl'dr. In this blog, I present my [matrix library](https://cp-algorithms.github.io/cp-algorithms-aux/cp-algo/linalg/matrix.hpp), which maintains a simple and elegant...
than utilizing the fact that the problem asks us to print the remainder modulo $998\;244\;353$, which, working with individual remainders modulo $2$, and instead try to batch the operations, so that, ` (take remainder modulo `mod`) or `pseudonormalize` (take remainder modulo `8*mod*mod`). 2. [vec

Full text and comments »

  • Vote: I like it
  • +259
  • Vote: I do not like it

84.
By MohammadParsaElahimanesh, 4 years ago, In English
Codeforces Global Round 23 Editorial Hi Codeforces, I've tried my best to make a different editorial, I wish you enjoy it ... [problem:1746A] problem author: [user:MohammadParsaElahimanesh,2022-10-15], [user:AmirrzwM,2022-10-15] <spoiler summary="step by step solution"> step 1: It's obvious that the answer is "NO" if $a_{i} = 0$ for all $1 \le i \le n$. step 2: Lets prove that the answer is "YES" if $a_{i} = 1$ for at least one $1 \le i \le n$. step 3: If size of $a$ is equal to $k$, just use second type operation once and we are done. step 4: Otherwise (if $|a| > k$), there will be three cases: (assume that $a_{j} = 1$) - if $j > 2$, you can use first type operation on first and second element and decrease size of $a$ by 1. - else if $j < |a|-1$, you can use first type operation on last and second to last element and decrease size of $a$ by 1. - else, it can be shown easily that $|a| = 3$ and $k = 2$ so you can use second type operation twice and turn $a$ into a single $1$. In ...
Consider the following coordinate system on a two-dimensional plane (modulo the addition of

Full text and comments »

85.
By SomethingNew, 4 years ago, In English
Codeforces Round #814 (Div. 1, Div. 2) Editorial Sorry for not very good samples, and late editorial. It was our first round, so it was wary stressful for us, But we hope you liked the problems despite this! [problem:1719A] <spoiler summary="Hint 1"> Try to look at the parity of $n, m$. </spoiler> <spoiler summary="Hint 2"> The player who wins does not depend on player's strategy. </spoiler> <spoiler summary="Hint 3"> The only thing that the winning player depends on is the parity of $n, m$. </spoiler> <spoiler summary="Tutorial"> Note that the game will end only when the chip is in the upper right corner (otherwise you can move it $1$ square to the right or up). For all moves, the chip will move $n - 1$ to the right and $m - 1$ up, which means that the total length of all moves is $n + m - 2$ (the length of the move is how much the chip moved per turn). Since the length of any move is odd, then after any move of Burenka, the sum of the lengths will be odd, and after any move of Tonya is even. So we can find...
Note that from the number $k$ we only need the remainder modulo $4

Full text and comments »

  • Vote: I like it
  • +129
  • Vote: I do not like it

86.
By 244mhq, 7 years ago, translation, In English
Editorial of Codeforces Round #572 Codes have been added! We've added challenges(mostly not hard) to some tasks. Feel free to share solutions and ask any questions in comments! Keanu Reeves ---------- If the string is good, then answer it's itself. Otherwise, there are at least two strings in answer, and we can print substring without its last symbol and its last symbol separately. Complexity $O(n)$. [code](https://pastebin.com/Dc0gtG9n) Number circle ---------- Let's suppose that array is sorted. First of all, if $a_n \ge a_{n - 1} + a_{n - 2}$, than the answer is &mdash; NO (because otherwise $a_{n}$ is not smaller than sum of the neighbors). We claim, that in all other cases answer is &mdash; YES. One of the possible constructions (if the array is already sorted) is: $a_{n - 2}, a_{n}, a_{n - 1}, a_{n - 4}, a_{n - 5}, \ldots ,a_1$ It's easy to see, that all numbers except $a_n$ will have at least one neighbor which is not smaller than itself. Complexity $O(nlog(n))$. [code](https://past...
Note that all numbers decreased by one modulo $k$. Because we've shown that applying our operation

Full text and comments »

  • Vote: I like it
  • +202
  • Vote: I do not like it

87.
By adamant, history, 4 years ago, In English
Oleksandr Kulkov Contest 3 in gym + tutorial and comments Hi everyone! As the [Universal Cup stage 7](https://codeforces.me/blog/entry/113640) which mirrored my contest from the [Osijek Competitive Programming Camp 2023](https://codeforces.me/blog/entry/113438) just concluded, I decided to also upload the contest to gym as [contest:104234], and post the tutorial here. I hope you enjoyed the contest! My previous ICPC-style contests: * [Oleksandr Kulkov Contest 1 in gym](https://codeforces.me/blog/entry/65678) * [Oleksandr Kulkov Contest 2 in gym](https://codeforces.me/blog/entry/72656) Compiled PDF Tutorial for all problems: [link](https://codeforces.me/gym/104234/attachments/download/19319/OKC3-tutorial.pdf). To make it worth a separate blog post, I will also add some brief meta comments :) P.S. Congratulations to the team **USA1** ([user:ecnerwala,2023-03-12], [user:ksun48,2023-03-12], [user:scott_wu,2023-03-12]) for solving all the problems in-contest! [cut]<br> ### [problem:104234A] Author: [user:adamant,2023...
generic modulo $m$. While it is considered standard fact that modulo $m$ is equivalent tomodulo $p^k

Full text and comments »

  • Vote: I like it
  • +76
  • Vote: I do not like it

88.
By flamestorm, 3 years ago, In English
April Fools Day Contest 2024 Editorial Thank you for participating in our contest! We hope you enjoyed it. Please let us know what you thought of the problems by voting! [problem:1952A] Idea: [user:flamestorm,2024-03-31] <spoiler summary="Hint"> Have you seen the "are you a robot" boxes on websites? </spoiler> <spoiler summary="Solution"> [problem:1952A] ------------------ If you select all the squares with traffic lights and read the corresponding letters from left-to-right, top-to-bottom, you get the text "$\texttt{print safety}$". So all you need to do is print the word $\texttt{safety}$. </spoiler> <spoiler summary="Feedback"> - Based problem - Based problem - Based problem </spoiler> [problem:1952B] Idea: [user:willy108,2024-03-31] <spoiler summary="Hint"> Can you interpret the question in the title another way? </spoiler> <spoiler summary="Solution"> [problem:1952B] ------------------ You just need to check if there ...
The modulo $20240401$ part is unnecessary as the answer can be at most $2$ (try to prove this

Full text and comments »

  • Vote: I like it
  • +182
  • Vote: I do not like it

89.
By adamant, history, 5 years ago, In English
Half-GCD algorithm Hi everyone! Today I'd like to finally talk about an algorithm to solve the following tasks in $O(n \log^2 n)$: - Compute the greatest common divisor of two polynomials $P(x)$ and $Q(x)$; - Given $f(x)$ and $h(x)$ find the multiplicative inverse of $f(x)$ modulo $h(x)$; - Given $F_0,F_1, \dots, F_m$, recover the minimum linear recurrence $F_n = a_1 F_{n-1} + \dots + a_d F_{n-d}$; - Given $P(x)$ and $Q(x)$, find $A(x)$ and $B(x)$ such that $P(x) A(x) + Q(x) B(x) = \gcd(P, Q)$; - Given $P(x)=(x-\lambda_1)\dots(x-\lambda_n)$ and $Q(x)=(x-\mu_1)\dots(x-\mu_m)$ compute their [resultant](https://en.wikipedia.org/wiki/Resultant). More specifically, this allows to solve in $O(n \log^2 n)$ the following problems: <hr> **[Library Checker &mdash; Find Linear Recurrence](https://judge.yosupo.jp/problem/find_linear_recurrence)**. You're given $F_0, \dots, F_{m}$. Find $a_1, \dots, a_d$ with minimum $d$ such that $$ F_n = \sum\limits_{k=1}^d a_k F_{n-k}. $$ <hr> <hr> **[Libr...
)$. Compute $f^{-1}(x)$ modulo $h(x)$. , This formula allows to find $\gcd(A, B)$ and a multiplicative inverse of $A(x)$ modulo $B(x)$ when

Full text and comments »

  • Vote: I like it
  • +179
  • Vote: I do not like it

90.
By RDDCCD, history, 11 months ago, In English
Please ban the users who use AI to participate in contests On the Global Round 31, user [user:Su_Zipei,2025-12-19] has just used AI to make it to the top 20 of the contest. Indeed, a smart contestant would not use overtly suspicious AI-generated code; those grey participants who rapidly solve the first six or seven problems in a competition can easily be identified as having used AI. A better approach is to obfuscate and polish the code provided by AI, or even rewrite it based on the AI's logic——for contestants with enough coding experience, this is quite straightforward. Clearly, compared to a 1200-rated player using AI to reach 1800, a 2400-rated player finds it easier to use AI to reach 3000. Still, we can find some evidence that is not so convincing. For those people who solve problem H1 fast enough, Kevin114514 uses 36 minutes, tourist uses 42 minutes, ecnerwala uses 32 minutes, while other pariticipants solves it even longer(~1h). However, Su_Zipei only solve it in 19 minutes, which is really, really fast. Another issue that req...
/354198220) uses captital letter "MOD" for modulo number. This is a rather rare habit because you

Full text and comments »

  • Vote: I like it
  • +358
  • Vote: I do not like it

91.
By platelet, history, 4 years ago, In English
speed test code speed test code of [this](https://codeforces.me/blog/entry/111566). ```cpp #include <bits/stdc++.h> using namespace std; const int N = 5e4, P = 998244353; int a[N]; void ThroughputTest() { int checkSum1 = 0, checkSum2 = 0, checkSum3 = 0; auto start = chrono::steady_clock::now(); for(int i = 0; i < N; i += 2) for(int j = 0; j < N; j++) { checkSum1 ^= (int64_t)a[i] * a[j] % P; checkSum1 ^= (int64_t)a[i + 1] * a[j] % P; } auto end = std::chrono::steady_clock::now(); cout << "Compiler's signed modulo: " << (end - start).count() * 1e-6 << " ms" << endl; start = chrono::steady_clock::now(); for(int i = 0; i < N; i += 2) for(int j = 0; j < N; j++) { checkSum2 ^= (uint64_t)(uint32_t)a[i] * (uint32_t)a[j] % P; checkSum2 ^= (uint64_t)(uint32_t)a[i + 1] * (uint32_t)a[j] % P; } end = std::chrono::steady_clock::now(); cout << "Compiler's unsigne...
Latency test(50000 * 25000): Compiler's signed modulo: 4329.33 ms Compiler's unsignedmodulo, ```plain Throughput test(50000 * 50000): Compiler's signed modulo: 1954.83 ms Compiler's

Full text and comments »

  • Vote: I like it
  • +67
  • Vote: I do not like it

92.
By Roundgod, history, 8 years ago, In English
[Tutorial] Inclusion-Exclusion Principle Hello, Codeforces! The reason why I am writing this blog is that my ACM/ICPC teammate [user:calabash_boy_love_15,2019-01-18] is learning this technique recently(he is a master in string algorithms,btw), and he wanted me to provide some useful resources on this topic. I found that although many claim that they do know this topic well, problems concerning inclusion-exclusion principle are sometimes quite tricky and not that easy to deal with. Also, after some few investigations, the so-called "Inclusion-Exclusion principle" some people claim that they know wasn't the generalized one, and has little use when solving problems. So, what I am going to pose here, is somewhat the "Generalized Inclusion-Exclusion Principle". Most of the describing text are from the graduate text book _Graduate Text in Mathematics 238, A Course in Enumeration_, and the problems are those that I encountered in real problem set, so if possible, I'll add a link to the real problem so that you can solve it by yours...
$ inversions, taken modulo $\relax 10^9+7$. Constraint: $1\leq N\leq 10^5,1\leq K\leq \min(10^5,\binom{N}{2})$., $, and their least common multiple is $\relax m$, taken modulo $\relax 998244353$.Constraint: $\relax, $, satisfying that $\relax 0\leq x_{i} < m$, modulo $\relax 998244353$. Constraints: $1\leq n,m,k\leq 10

Full text and comments »

  • Vote: I like it
  • +323
  • Vote: I do not like it

93.
By qwexd, 3 months ago, In English
Codeforces Round 1121 (Div. 2) Editorial # Codeforces Round 1121 — Editorial Thanks for participating! ### [problem:2264A] Problem by [user:qwexd,2026-09-13]. <spoiler summary="Hint"> Look at the elements that are not in the right position. Which of them must be selected? Can selecting any other element help? </spoiler> <spoiler summary="Solution"> Every element that is not in the right position has to be selected; otherwise, it never moves. Selecting an element that is already in the right position cannot help. For it to stay correct after the reversal, it has to be paired with itself, because its value occurs nowhere else in the permutation. Thus it can only be the middle selected element, and removing it changes nothing. So, if the array is already sorted, choose any one element. Otherwise, select exactly the misplaced elements and reverse them. The answer is `YES` if this sorts the array, and `NO` otherwise. If the misplaced positions are listed from left to right, the reversal pairs the...
Modulo $3$, the powers of $2$ alternate between $1$ and $-1$. Define the alternating prefix sum

Full text and comments »

  • Vote: I like it
  • +149
  • Vote: I do not like it

94.
By -firefly-, history, 16 months ago, In English
Codeforces Round 1042 (Div. 3) Editorial I hope you all enjoyed the contest! <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | H | |------------------------------------|--------|--------|--------|--------|--------|--------|--------|--------| | [user:AksLolCoding,2025-08-10] | 800 | 900 | 1000 | 1400 | 1500 | 1800 | 1800 | &mdash; | | [user:ALnQ417,2025-08-10] | 800 | 900 | 1100 | 1300 | 1500 | 1600 | &mdash; | &mdash; | | [user:bookcat,2025-08-10] | 800 | 1200 | 1200 | 1500 | 1600 | 1600 | 1600 | 2000 | | [user:chromate00,2025-08-10] | 800 | 800 | 1000 | 1400 | 1400 | 1800 | 1800 | 2200 | | [user:cry,2025-08-10] | 800 | 1000 | 1200 | 1600 | 1700 | 2100 | 2100 | 2400 | | [user:Edeeva,2025-08-10] | 800 | 800 | 1000 | 1300 | 1400 | 1600 | 1900 | &mdash; | |...
Consider the operations modulo $k$.

Full text and comments »

  • Vote: I like it
  • +110
  • Vote: I do not like it

95.
By TheScrasse, 3 years ago, In English
Editorial of Codeforces Round 889 (Div. 1 + Div. 2) The official implementations of all the problems are [here](https://drive.google.com/file/d/1stkidhN_ftTOzK4qcMYxkUAlwWWb3AqF/view?usp=sharing). [problem:1855A] Author: [user:Kaey,2023-07-23]<br> Preparation: [user:akifpatel,2023-07-23] <spoiler summary="Hint 1"> What's the most efficient way to make the sad students happy? </spoiler> <spoiler summary="Hint 2"> In most cases, you can make $2$ sad students happy in $1$ move. </spoiler> <spoiler summary="Solution"> Let $s$ be the number of sad students at the beginning. The answer is $\lceil \frac{s}{2} \rceil$. In one move, you can make at most $2$ sad students happy (because you can change the position of at most two students), so you need at least $\lceil \frac{s}{2} \rceil$ moves. In fact, you can make everyone happy in exactly $\lceil \frac{s}{2} \rceil$ moves: - while there are at least $2$ sad students, you can swap them and both of them will be happy; - if there is exactly $1$ sad student left, you ...
looking at the values in $[l, r]$ modulo $x$). Then, the interval $[1, r-l+1]$ is also valid and has

Full text and comments »

  • Vote: I like it
  • +196
  • Vote: I do not like it

96.
By tunyash, 14 years ago, translation, In English
Editoral Codeforces Round #122 Please, report me about every grammar mistake, you see. Thank you. **Problem <<Exams>>** Let's notice that $2n \le k \le 5n$. If $k < 3n$ author has to get $2$ on some exams. There are $3n-k$ such exams and that's the answer). If $3n \le k$ author will pass all exams (answer is $0$). **Problem <<Square>>** Let the pencil move by the line and put crosses through every $(n+1)$ point. Lets associate every point on the line with point on square perimeter. Namely, point $x$ on the line will be associated with point on square perimeter that we will reach if we move pencil around square to $x$ clockwise. Then lower left corner will be associated with all points $4np$ for every non-negative integer $p$. Crosses will be associated with points $k(n+1)$ for some non-negative $k$. Nearest point of overlap of two families of points will be in point LCM($n+1$, $4n$). Then we will put $\frac{LCM(n+1,4n)}{n+1} + 1$ crosses. **Problem "Cutting Figure"** Translation by [user:moskupo...
\mod b$. - Find all occurences of number $f \mod a$ in Fibonacci sequence modulo $a$ period, sequence modulo $10^p$ (for any natural $p$) is not big more efficiently. From occurences in, In this problem we had some Fibonacci number modulo $10^{13}$ $f$, and we had to determine the

Full text and comments »

  • Vote: I like it
  • +116
  • Vote: I do not like it

97.
By Proof_by_QED, history, 7 weeks ago, In English
About example test cases I'm the coordinator of [contest:2261]. After the contest ended, I am disappointed to see some people complaining about the weak samples in the comments of the announcement. I agree that the samples in some problems (A, C, D1) are weak. But this was an intentional decision during the problem preparation process, and I am here to defend this decision. This post will contain an overview of what I believe samples should be used for, what good samples (not necessarily strong samples) look like from both a participant and problemsetting point of view. ### What are samples for? The most important function of samples and notes are for making sure the participant understands the problem statement. If samples and notes do not clarify confusion a participant may have about the problem after reading the statement carefully, I would say that's a bad set of samples. The second function of samples, especially for interactive and constructive problems, are for showing the output/interaction ...
generate a strong, large case where the answer is large or even exceed modulo, so it serves as a great way

Full text and comments »

  • Vote: I like it
  • +191
  • Vote: I do not like it

98.
By paulzrm, history, 4 months ago, In English
Codeforces Round 1116 (Div. 1, Div. 2) Editorial [2256A-Three Numbers on the Blackboard](https://codeforces.me/contest/2256/problem/A) Idea: [user:paulzrm,2026-08-10] <spoiler summary="Hint 1"> Sort the numbers as $a\le b\le c$. </spoiler> <spoiler summary="Hint 2"> After at least one operation, consider the median. </spoiler> <spoiler summary="Hint 3"> Doing nothing gives $c-a$; replacing $c$ with $a+b$ gives $b$. </spoiler> <spoiler summary="Tutorial"> Suppose the current numbers are $x\le y\le z$. An operation keeps two numbers and replaces the third with their sum. Since all values are nonnegative, the new sum is no smaller than either retained number. Thus the new median is the larger retained number, which is at least the old median $y$. The median never decreases. After an operation that retains $u\le v$, the numbers are $u,v,u+v$. Their range is exactly $v$, also their median. Hence every nonempty sequence of operations ends with a range of at least the initial median $b$. With no opera...
and record afterward. Decode online input modulo $2^{64}$ exactly as specified., Let $w$ be the number of black cells and $S_r,S_c$ their coordinate sums modulo $n$. Observe how

Full text and comments »

  • Vote: I like it
  • +166
  • Vote: I do not like it

99.
By mango_lassi, history, 6 years ago, In English
Finding minimum residue of a linear function in O(log M) time I saw [a blog](https://codeforces.me/blog/entry/90585) (thanks to [user:bugman,2021-05-14] for finding it!) earlier today asking how to solve the following problem: _Given a linear function $ax + b$, find the minimum $x \geq 0$ such that $ax + b \in [L, R]\ (\text{mod } M)$_. To solve that problem, we can make the following reduction: If $gcd(a, M) > 1$, we divide everything by the GCD. The $x$ for which $ax + b = L\ (\text{mod } M)$ is $(L - b) a^{-1}\ (\text{mod } M)$. Denote this value by $b_0$. Then, the minimum $x$ to get to $L + y$ is $a^{-1} y + b_0\ (\text{mod } M)$. This gives us a reduced problem: _Find the minimum value of $ay + b \text{ mod } M$ over $y \leq k$_. This seemed pretty hard, but surprisingly I figured out how to do it in $\mathcal{O}(\log M)$ time! The algorithm is as follows: In every step, we reduce the modulo from $M$ to $\min(a, M - a) \leq M / 2$. This guarantees we do at most $\mathcal{O}(\log M)$ steps. To reduce it to $a$, we consider...
In every step, we reduce the modulo from $M$ to $\min(a, M - a) \leq M / 2$. This guarantees we do

Full text and comments »

  • Vote: I like it
  • +179
  • Vote: I do not like it

100.
By jerrywang0916, history, 8 months ago, In English
List of Suspected Cheaters in Nebius Round 2 This message was originally intended to be posted via the account [user:send_cheater_to_basement,2026-03-31]. However, since that account is not a trusted account, it cannot publish blogs. Therefore, I am using this account instead, **which belongs to one of my classmates**. I would like to thank him for lending it to me. I manually collected all suspicious users, which were then organized by AI. There may be errors. Here is a list of users who are heavily suspected of cheating during the Nebius Round 2. I only managed to check the top 250 participants whose original rating was no higher than Specialist. Unfortunately, I had to stop after checking these because my IP was flagged as a web crawler/bot. **⚠️ DISCLAIMER: Appearing on this list does not definitively prove that a user has cheated.** It simply indicates highly suspicious behavior during the contest. ### Detection Methodology During the contest, anti-AI traps were placed in the problem statements: - ...
modulo."_

Full text and comments »

  • Vote: I like it
  • +264
  • Vote: I do not like it

101.
By Anadi, history, 8 years ago, In English
Codeforces Round #519 Editorial #### [1043A &mdash; Elections](http://codeforces.me/contest/1043/problem/A) <spoiler summary="Tutorial"> We can observe that result cannot exceed $201$ &mdash; Awruk gets at least $101$ votes from one person and Elodreip cannot get more than $100$ votes from one person. So we can iterate over every possible integer from $1$ to $201$ and check if Awruk wins with $k$ set to this integer. We have to remember that $k$ &mdash; $a_i$ is always at least $0$, so we have to check this condition too. Complexity $O(n * M)$, where $M$ denotes maximum possible value of $a_i$. Try to solve it in $O(n)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int n; int mx = 0, sum = 0; int main(){ scanf("%d", &n); for(int i = 1; i <= n; ++i){ int a; scanf("%d", &a); mx = max(mx, a); sum += a; } sum *= 2; sum += n; sum /= n; printf("%d", max(sum, mx)); return 0; } ~~~~~ </spoiler> Author: [user:FCB1234,201...
we should compute it modulo some big prime.

Full text and comments »

  • Vote: I like it
  • +113
  • Vote: I do not like it

102.
By ditoly, history, 8 years ago, In English
Codeforces Round #511 Editorial Hi, here is the editorial. Sorry for a long waiting. Have you enjoyed this round? I hope so. I know there are many things not so good and making some people unhappy :( I'm very sorry about that. Since this is my first round, I have many things not taken into consideration or done badly. I will try to improve them if I have my next round (I hope). Let's talk about the problems. The problems are mainly prepared by me, [user:ditoly,2018-09-22], which can be seen in D1D as "Little D". Also, my friends [user:ACMLCZH,2018-09-22] ("Little C") and [user:FallDream,2018-09-22] ("Mr. F", I don't know whether this name can explain Chinese word "F大爷" well, maybe "Master F" is better?) provided great helps. The statements are mainly written by me (with the help of [user:300iq,2018-09-22] and [user:cyand1317,2018-09-22] and some others, thanks!). My English is not so good, so it's frequent that I just understand the problem but other people get AC :( So I try to explain the problems in short st...
you mistake the modulo number or do not modulo :D I guess the answer will be about $O(n\text{log, But in fact, we only care $\frac{f_i}{p^{BC(i)}}$ modulo $p$, so we can let all number bemodulo $p, In fact, when the answer is modulo $p$, an arbitrary integer, my solution works., In this problem, we only need to calculate $c_i\&3$, equal to $c_i$ modulo $4$., modulo $p$ which $p$ is a small integer now, I can solve with modulo $10^9+7$ using 1024-bit computers

Full text and comments »

  • Vote: I like it
  • +191
  • Vote: I do not like it

103.
By Radewoosh, history, 11 years ago, In English
VK Cup 2016 — Round 3 — Editorial Editorial was created by [user:Errichto,2016-05-07], but he said that he has enough contribution, so I'm posting it for you. ;) #1 [problem:673A] (invented by [user:GlebsHP,2016-05-07] &mdash; thanks!) You are supposed to implement what is described in the statement. When you read numbers $t_i$, check if two consecutive numbers differ by more than $15$ (i.e. $t_i - t_{i-1} > 15$). If yes then you should print $t_{i-1}+15$. You can assume that $t_0 = 0$ and then you don't have to care about some corner case at the beginning. Also, you can assume that $t_{n+1} = 91$ or $t_{n+1} = 90$ (both should work &mdash; do you see why?). If your program haven't found two consecutive numbers different by more than $15$ then print $90$. If you still have problems to solve this problem then check codes of other participants. [submission:18286606] #2 [problem:673B] (invented by [user:Errichto,2016-05-07]) Some prefix of problems must belong to one division, and the remaining suf...
unsigned long long's) and only then compute modulo. You would then get very fast solution.

Full text and comments »

Tutorial of VK Cup 2016 - Round 3
  • Vote: I like it
  • +109
  • Vote: I do not like it

104.
By AksLolCoding, history, 20 months ago, In English
My Editorials for 1011 (Div. 2) For implementations, see my submissions #A &mdash; Serval and String Theory <spoiler summary="Solution"> It is only impossible if the number of k is 0 and r is not universal, or if r consists of only one distinct character. Time complexity: $O(n)$ </spoiler> #B &mdash; Serval and Final MEX <spoiler summary="Solution"> For the MEX to be 0, we must remove all 0s from the array and then apply the operation on the whole array. We can remove all zeroes in one operation (with endpoints on the leftmost and rightmost zeroes) unless both the first and last element are 0, in which case it takes two operations. Once all zeros are removed, we can MEX the whole array resulting in 0. Time complexity: $O(n)$ </spoiler> #C &mdash; Serval and The Formula <spoiler summary="Solution"> It is always possible if x != y. WLOG, assume x>y. Note that a+b=a^b (^ is xor) if and only if the bitwise and of a and b is 0. Let M be the least power of 2 greater than or equal to x. Using k = ...
#E — Serval and Modulo

Full text and comments »

  • Vote: I like it
  • +31
  • Vote: I do not like it

105.
By Ripatti, 15 years ago, translation, In English
Croc Champ 2012 — Round 1 — Editorial **A.** Naive solution in $O(n)$ (some simulation all of n rounds) gets TL. Let's speed up this solution. Let's consider rounds on segments [1..mk], [mk+1..2mk], [2mk+1..3mk] and so on. You can see that results of games on these segments will repeat. So you can simulate over exactly one segment and then take into consideration them [n/(mk)] times ([x] is rounding down). Remainder of n%(mk) last rounds you can simulate separately. So you have $O(mk)$ solution that easily fits into time limits. Authors are ~Ripatti,2012-04-06 and ~Gerald,2012-04-06 [cut] . **B.** In this problem you should build bipartite graph with n+m vertices. All vertices of the firts part correspond to the rows of the table, vertices of the second part correspond to the columns of the one. Edge connects vertices iff some regular column is placed in the cross of corresponding row and column. Firstly death ray covers only last row of the table that corresponds to one of vertices of our graph. When you are ch...
Otherwise we can note then size of the first part is 1 modulo 3 and size of the second part is 2

Full text and comments »

  • Vote: I like it
  • +103
  • Vote: I do not like it

106.
By AnandOza, history, 6 years ago, In English
Atcoder Beginner Contest 174 — Unofficial English Editorial Hi all, [Atcoder Beginner Contest 174](https://atcoder.jp/contests/abc174) was today. I wrote an unofficial English editorial. Hope it helps! ### [A: Air Conditioner](https://atcoder.jp/contests/abc174/tasks/abc174_a) We simply write an if statement. Runtime: $\mathcal{O}(1)$. <spoiler summary="Sample code"> ~~~~~ int x = in.nextInt(); out.println(x >= 30 ? "Yes" : "No"); ~~~~~ </spoiler> ### [B: Distance](https://atcoder.jp/contests/abc174/tasks/abc174_b) We can loop through all the points, and test each one. To avoid potential rounding errors, it's simplest to check $x^2 + y^2 \le D^2$, so we can keep everything in integers. Runtime: $\mathcal{O}(N)$. <spoiler summary="Sample code"> ~~~~~ int n = in.nextInt(); long d = in.nextInt(); d = d * d; Point[] points = Point.readPoints(in, n); int answer = 0; for (Point p : points) { if (p.x * p.x + p.y * p.y <= d) answer++; } out.println(answer); ~~~~~ </spoiler> ### [C: Repsept](h...
$ modulo $k$. Then we have at most $k-1$ distinct values (modulo $k$), so by pigeonhole there exist

Full text and comments »

  • Vote: I like it
  • +131
  • Vote: I do not like it

107.
By feecIe6418, history, 2 years ago, In English
Editorial of Codeforces Round 958 (Div. 2) Thanks for participation! **Update**: added alternative solutions/proofs for A,B,D,F [problem:1988A] <spoiler summary="Hint 1"> The optimal sequence of operations is very simple. </spoiler> <spoiler summary="Solution"> The optimal sequence of operations is adding $k-1$ 1-s into the set each time, at the same time decreasing $n$ by $k-1$. This implies that the answer is $\lceil \frac{n-1}{k-1}\rceil$. <spoiler summary="Why?"> I failed to find a Div2-A level proof. If you have a simpler proof please share it in the comments. Consider the number of elements that is $\equiv 1\pmod{(k-1)}$ in the set. The number of such elements increase by at most $k-1$ in each operation, and the aforementioned sequence of operation achieves the maximum increment. --- A simpler proof in the comments: consider the number of elements in the set. It increases by at most $k-1$ each time, and our construction reaches the maximum increment. </spoiler> </spoiler> <spoiler summar...
problem can also be solved with modulo $10^9+7$ or on an algebraic structure where FFT is not easy, but

Full text and comments »

  • Vote: I like it
  • +147
  • Vote: I do not like it

108.
By Errichto, 10 years ago, In English
Good Bye 2016 — hints and codes You can download my codes to all problems [here](http://www.filedropper.com/codes_1). I will write a full editorial in the next few days. Now you can read hints and short solutions. [problem:750B] <spoiler summary="hint"> Create a variable that will denote your current distance from the North Pole. What are allowed values of this variable? When can't we go West or East? </spoiler> [problem:750C] <spoiler summary="hint1"> Let $x$ denote the initial rating (or his final rating, whatever is easier for you to think about). The information that Limak is in some division in the $i$-th contest gives us some inequality for $x$. Can you see it? </spoiler> <spoiler summary="hint2"> For every contest we know that the current rating is $x$ increased by some prefix sum of c_i (changes of rating). If Limak is in the division 1, we have inequality x+prefSum >= 1900 so we have x >= 1900-prefSum. If Limak is in the division 2, we have inequality x_prefSum <= 1899 so it is ...
$ modulo $8$. You can add memoization to this slow code yourself and try to get AC.

Full text and comments »

Tutorial of Good Bye 2016
  • Vote: I like it
  • +168
  • Vote: I do not like it

109.
By adamant, history, 5 years ago, In English
Fast polynomial composition Hi everyone! Today I want to describe an efficient solution of the following problem: <hr> **[Composition of Formal Power Series](https://judge.yosupo.jp/problem/composition_of_formal_power_series)**. Given $A(x)$ and $B(x)$ of degree $n-1$ such that $B(0) = 0$, compute $A(B(x)) \pmod{x^n}$. <hr> The condition $B(0)=0$ doesn't decrease the generality of the problem, as $A(B(x)) = P(Q(x))$, where $P(x) = A(x+B(0))$ and $Q(x) = B(x) - B(0)$. Hence you could replace $A(x)$ and $B(x)$ with $P(x)$ and $Q(x)$ when the condition is not satisfied. Solutions that I'm going to describe were published in Joris van der Hoeven's [article](https://www.sciencedirect.com/science/article/pii/S0747717102905626) about operations on formal power series. The article also describes a lot of other common algorithms on polynomials. It is worth noting that Joris van der Hoeven and David Harvey are the inventors of the breakthrough $O(n \log n)$ [integer multiplication algorithm](https://hal.archi...
You could compute $B^2(x), B^3(x), \dots, B^{n-1}(x)$ modulo $x^n$ one by one and sum them up

Full text and comments »

  • Vote: I like it
  • +133
  • Vote: I do not like it

110.
By RP-1, 20 months ago, In English
Sqrt Heuristic for Floor Sums _Thanks to [user:Kapt,2025-04-10] for proofreading this blog._ Recently, I came across a couple of AtCoder problems on modular arithmetic. In short, they both involved sequences $\\{ A, A+C, A+2C, \dots \\}$ modulo $M$. The usual way to deal with these sequences is floor sums: **Problem (Floor Sum).** Calculate $\displaystyle \sum_{k=0}^n \left\lfloor \frac{Ck+A}{M} \right\rfloor$. This is solvable in $O(\log M)$ with a recursive Euclid-like algorithm. If you want to learn more about floor sums, I recommend [this blog](https://asfjwd.github.io/2020-04-24-floor-sum-ap/) by [user:_timelord,2025-04-10]. However, what I want to show you is how you can solve problems like that with a completely different idea. The basis of our reasoning is the following statement: (For the rest of this blog, let $0 \le C, A < M$, $\gcd(C, M) = 1$, $n < M$, just to avoid hassle.) **Statement.** The sequence $\\{A, C + A, 2C + A, \dots, Cn + A\\} \bmod M$ can be split into $O(\sqrt{M})$ d...
independently for each residue modulo $H$., involved sequences $\\{ A, A+C, A+2C, \dots \\}$ modulo $M$. The usual way to deal with these sequences, Summing this result over all remainders modulo $d$, we get $O(d + \frac{nH}{M})$ arithmetic

Full text and comments »

  • Vote: I like it
  • +161
  • Vote: I do not like it

111.
By EJIC_B_KEDAX, history, 2 years ago, translation, In English
Quadratic residue by prime modulus [TUTORIAL] Hello, Codeforces! Today I'm going to talk about an unpopular technique in number theory. Definition and elementary properties ------------------ **Def.** Let $p > 2$ be a prime number, then we will call *quadratic residues* all $1 \le x \le p - 1$ modulo $p$ such that the equation $a^2 \equiv x \pmod{p}$ has solutions and *quadratic nonresidues* otherwise. **Note** that $0$ is neither *quadratic residue* nor *quadratic nonresidue*. **Theorem:** quadratic residues and quadratic nonresidues are equally divided. <spoiler summary="Proof">. Consider the situation where $x^2 \equiv y^2 \pmod{p}$, this is equivalent to saying that $x^2 - y^2 \equiv 0 \pmod{p}$. Using the difference-of-squares formula, we get $(x - y) \cdot (x + y) \equiv 0 \pmod{p}$. It follows that either $x - y \equiv 0 \pmod{p}$ or $x + y \equiv 0 \pmod{p}$, that is, either $x \equiv y \pmod{p}$ or $x \equiv -y \pmod{p}$. It turns out that all numbers split into pairs $x$ and $-x$, so each quadratic resi...
Finding $i$ modulo $p$ ------------------ **Def.** $i$ is such a number that $i^2 = -1$ $\implies

Full text and comments »

  • Vote: I like it
  • +101
  • Vote: I do not like it

112.
By box, 5 years ago, In English
On the Min25 sieve and extensions / SPOJ ASSIEVE Consider the following problem (general form of original Min25 sieve): We are given some *multiplicative* function $f(n)$, described at prime powers by $f(p^k)=g(p,k)$, where $g(p,1)$ is a polynomial of low degree, and we can calculate $g(p,k)$ for any singular $p$ and $k$ in $O(1)$. How do we calculate the prefix sum of $f(n)$ at the distinct positive integer values of $\lfloor\frac Nk\rfloor$, where $N\le 10^{10}$? Clearly, brute force or regular sieves are not going to cut it here. --- Prerequisite: For any integer $N$, for all integers $1\le k\le N$ there are at most $2\sqrt N$ distinct values of $\lfloor\frac Nk\rfloor$. Call these $2\sqrt N$ such values the *blocks* of $N$. (A note on notation: In the following text, $\frac Nk$ will be used to describe regular division, and $N/k$ will be used to denote floored division.) <spoiler summary="Proof"> For $k\le\sqrt N$, each $k$ contributes at most one distinct value, for a total of $\sqrt N$ elements. For $k>\sqrt ...
these composites can all be expressed in the form $pd$. Now, we can do casework on $p$modulo $4

Full text and comments »

  • Vote: I like it
  • +161
  • Vote: I do not like it

113.
By errorgorn, 5 years ago, In English
Pragma Insanity: Weird Behaviour with Pragma O3 Here is a simple problem. Count the number of array $A$ of non-negative integers size $N$ such that $\sum\limits_{i=1}^{N} A_i \cdot i=K$. Where $N,K \leq 5000$. Find the answer modulo $1000000007$. I unfortunately cannot share the link to a submissions page as it is on a private local judge. Update: I have asked judge devs of the local judge, the compile command is `g++ -O2 -o {compiledName} {sourceName} -m64 -static -std=gnu++14 -lm -s -w -Wall -Wshadow -fmax-errors=512` But anyways, here is the problem. <spoiler summary="AC code"> ~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include <bits/stdc++.h> using namespace std; #define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--)) const int MOD=1000000007; int n,k; int memo[5005]; int main(){ cin>>n>>k; memo[k]=1; rep(x,n+1,1) if (k>=x) rep(y,k+1,x){ assert(y-x>=0); memo[y-x]=(memo[y-x]+...
$\sum\limits_{i=1}^{N} A_i \cdot i=K$. Where $N,K \leq 5000$. Find the answer modulo $1000000007$.

Full text and comments »

  • Vote: I like it
  • +122
  • Vote: I do not like it

114.
By TooNewbie, 9 years ago, In English
[Tutorial] Invariants and Monovariants Hello Codeforces! Some months ago I wrote tutorial about [basics of recurrent sequences](http://codeforces.me/blog/entry/54154). This blog, my second tutorial is about mine another favorite topic &mdash; Invariants and Monovariants. These are useful concepts which will help you solving problems, especially, constructive ones. Even if you are not familiar with this topics, I'm sure that you solved problems with use of invariants and monovariants without knowing it, continue reading, you will understand my point :) There will be hard problems which are based on old IMO problems, so I will try my best to explain solutions of examples. So, what are Invariants and Monovariants? An invariant is a quantity that doesn't change. A monovariant is a quantity that changes monotically (that is, non-decreasing or non-increasing). Seems simple, yes? Let's start with a few easy examples which you will better understand its point. I suggest you to try solving problems by your own before reading ...
. We will use one well known fact to solve problem — $S(n) - n$ is invariant in modulo 9, it is

Full text and comments »

  • Vote: I like it
  • +293
  • Vote: I do not like it

115.
By purplesyringa, history, 5 years ago, In English
Kapun's algorithm I'd like to share this one unpopular but awesome algorithm that I only heard a mention of once. Kapun's algorithm finds a hash collision for moduli as large as $10^{18}$. I know, we have *lots* of algorithms that do much better than that (and I'm writing an article on that at the moment, keep tuned), but Kapun's algorithm is really surprising in its simplicity. That its correctness is so difficult to prove is of more surprise even. Here we go. A polynomial hash of a string $s$ is defined as $$ H(s) = s_0 b^0 + s_1 b^1 + s_2 b^2 + \dots + s_{n-1} b^{n-1} \pmod M. $$ We want to find two strings with the same polynomial hash using only two characters: $0$ and $1$. We can reformulate this problem in another way. Let $a_i = b^i \mod M$, then we want to find two distinct subsets of $a$ with the same sum modulo $M$. Now *forget about the modulus*: let's just find two subsets with the same sum. Firstly, when is this possible? There are $2^n$ possible subsets and $n(M - 1) -...
distinct subsets of $a$ with the same sum modulo $M$. Now *forget about the modulus*: let's just find

Full text and comments »

  • Vote: I like it
  • +246
  • Vote: I do not like it

116.
By 055D, 6 years ago, In English
Codeforces Round #665 (Div. 2) Editorial Thank you for participating. I hope you enjoyed the contest! [problem:1401A] <spoiler summary="Tutorial"> [tutorial:1401A] </spoiler> <spoiler summary="Solution Code"> ~~~~~ #include<bits/stdc++.h> #define endl '\n' using namespace std; main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int k, n, t; cin >> t; for(;t--;) { cin >> n >> k; if(n < k) cout << k - n << endl; else if(n % 2 == k % 2) cout << 0 << endl; else cout << 1 << endl; } return 0; } ~~~~~ </spoiler> <spoiler summary="Behind Story"> After 2 problems got rejected, I made this problem but it has 2D coordinate originally. </spoiler> [problem:1401B] <spoiler summary="Tutorial"> [tutorial:1401B] </spoiler> <spoiler summary="Solution Code"> ~~~~~ #include<bits/stdc++.h> #define endl '\n' using namespace std; main() { ...
. And the modulo was new one originally, but I changed it later by myself.

Full text and comments »

  • Vote: I like it
  • +221
  • Vote: I do not like it

117.
By cadmiumky, 2 years ago, In English
Height-wise Small-to-Large Trick Hello Codeforces, I will present today, and in any day in the future, a means to correctly calculate a corner case of the well known small-to-large trick, and how this can be employed to solve a set of certain problems. This blog is written with encouragement from the [Month of Blog Posts](https://codeforces.me/blog/entry/133806) initiative. <spoiler summary="Forenote; Height definition"> The *height* of a node, as will be used throughout this blog, refers to the maximum distance in a rooted tree from a node to any of the leaves within its subtree. As a corollary, hereby it is considered that a leaf has a height of 1. </spoiler> ### The standard example. Let's try to solve the following problem: [Cat In a Tree, BOI 2017](https://oj.uz/problem/view/BOI17_catinatree). Although this problem can be solved employing some greedy algorithm, assume we have no idea what greedy is or how it could be correct, and revert to the basics: #### The standard DP. How can we formul...
$ and $R$ (Modulo $10^9+7$).

Full text and comments »

  • Vote: I like it
  • +208
  • Vote: I do not like it

118.
By wakanda-forever, 7 months ago, In English
Codeforces Round 1095 (Div. 2) Editorial Thanks for participating. We hope you liked the problems and enjoyed the round. #### [problem:2226A] Idea: [user:wakanda-forever,2026-04-21] <br> Preparation: [user:wakanda-forever,2026-04-21] <br> Solution: [user:wakanda-forever,2026-04-21] <br> <spoiler summary = "Solution"> For any two positive integers $x$ and $y$, observe that $x \times y \ge x + y$ when $x > 1$ and $y > 1$. Thus, it is never optimal to choose two elements that are more than $1$ in a single operation. Also, it is optimal to choose as many $1$'s as possible in a single operation. Hence, we opt to choose subsequences of the form $[1, 1, \ldots, x]$ and delete them. Note that the cost for this operation is equal to $x$. Therefore, the answer is just the sum of elements that are more than $1$. But if the last element is $1$, it cannot be clubbed with any "more than $1$ element", and it adds $1$ to the answer. Time Complexity: $\mathcal{O(n)}$ </spoiler> <spoiler summary = "Implementation"> ...
taken modulo $998244353$.

Full text and comments »

  • Vote: I like it
  • +86
  • Vote: I do not like it

119.
By AnandOza, history, 6 years ago, In English
Atcoder Beginner Contest 171 — Unofficial English Editorial Hi all, [Atcoder Beginner Contest 171](https://atcoder.jp/contests/abc171) was today. I wrote an unofficial English editorial. Hope it helps! ### [A: αlphabet](https://atcoder.jp/contests/abc171/tasks/abc171_a) We simply write an if statement. Runtime: $\mathcal{O}(1)$. <spoiler summary="Sample code"> ~~~~~ char x = in.next().charAt(0); if (x >= 'A' && x <= 'Z') out.println("A"); else out.println("a"); ~~~~~ </spoiler> ### [B: Mix Juice](https://atcoder.jp/contests/abc171/tasks/abc171_b) We want to buy the cheapest fruits, so we can sort the array and then pick the first $K$ fruits. Runtime: $\mathcal{O}(N \log N)$. <spoiler summary="Sample code"> ~~~~~ int n = in.nextInt(), k = in.nextInt(); int[] p = in.readIntArray(n); Util.safeSort(p); // this shuffles and sorts to avoid hacks long answer = 0; for (int i = 0; i < k; i++) { answer += p[i]; } out.println(answer); ~~~~~ </spoiler> ### [C: One Quadrillion and One Dalmatia...
looking at the value modulo $26$. Then to shift everything over, we divide by $26$, and repeat the

Full text and comments »

  • Vote: I like it
  • +256
  • Vote: I do not like it

120.
By SecondThread, 6 years ago, In English
SecondThread vs. galen_colin Lockout Duel (ft. neal, stevenkplus) SecondThread vs. galen_colin Lockout Duel (ft. neal, stevenkplus) ================== Good morning everyone! There are three great unsolved questions on Codeforces that every pupil dreams to one day know the answer to: - What's the best opening move when playing the Epsilon Guessing Game against a geometry problem? - How many cyans is [user:Um_nik,2020-11-27] worth, modulo $10^9+7$? - Who is *really* the 229th best programmer on Codeforces: [user:SecondThread,2020-11-27] or [user:galen_colin,2020-11-27]? While we may never know the answer to the first two, Colin and I will settle the third question once and for all this Sunday in a 1v1 duel! Don't miss it! ![ ](http://wumbogames.github.io/cfPictures/yugi.jpg) Join us at [this time on Sunday](https://www.timeanddate.com/worldclock/fixedtime.html?msg=SecondThread+vs.+galen_colin+Lockout&iso=20201129T0830&p1=234&ah=1) where we will compete head-to-head in a 1v1 lockout at https://www.twitch.tv/nealwu, with live commen...
? - How many cyans is [user:Um_nik,2020-11-27] worth, modulo $10^9+7$? - Who is *really* the 229th

Full text and comments »

  • Vote: I like it
  • +464
  • Vote: I do not like it

121.
By adamant, history, 5 years ago, In English
Basis change in linear recurrences Hi everyone! Today I'd like to write about Fibonacci numbers. Ever heard of them? Fibonacci sequence is defined as $F_n = F_{n-1} + F_{n-2}$. It got me interested, what would the recurrence be like if it looked like $F_n = \alpha F_{n-p} + \beta F_{n-q}$ for $p \neq q$? <hr> **[Timus &mdash; Fibonacci Sequence](https://timus.online/problem.aspx?space=1&num=1133)**. The sequence $F$ satisfies the condition $F_n = F_{n-1} + F_{n-2}$. You're given $F_i$ and $F_j$, compute $F_n$. <hr> Using $L(x^n) = F_n$ functional, we can say that we essentially need to solve the following system of equations: $$1 \equiv \alpha x^{-p} + \beta x^{-q} \pmod{x^2-x-1}.$$ To get the actual solution from it, we should first understand what exactly is the remainder of $x^n$ modulo $x^2-x-1$. The remainder of $P(x)$ modulo $(x-a)(x-b)$ is generally determined by $P(a)$ and $P(b)$: $$ P(x) \equiv r \mod(x-a)(x-b) \iff \begin{cases}P(a) = r,\\ P(b)=r.\end{cases} $$ Therefore, our equation a...
^n$ modulo $x^2-x-1$. The remainder of $P(x)$ modulo $(x-a)(x-b)$ is generally determined by $P(a

Full text and comments »

  • Vote: I like it
  • +172
  • Vote: I do not like it

122.
By rng_58, history, 10 years ago, In English
Tips for writers: What requires a proof? If you are a contestant, you can be relaxed and you can do anything (except for cheating). It's perfectly fine if you just guess the solution and submit it without knowing why (though personally I don't find it very beautiful). However, if you are a writer, you need to prove your solution. Here is the list of things you have to prove: #### 1. Correctness. Does your solution always return correct answers for all possible valid inputs? - GOOD: Strict proof. - BAD: _My intuition tells that this is correct!_ - BAD: _I tried really hard to come up with counterexamples, but I couldn't. It must be correct!_ #### 2. Time Complexity. Does your solution always run in time for all possible valid inputs? - GOOD: It's $O(n^2)$ and the constraints say $n \leq 1000$. It should work. - GOOD: For this problem we can prove that the slowest case is xxx. Experimentally, my solution works for the input xxx under the given TL. - BAD: _I tried really hard to generate various testcases, and ...
compute $10^5$ hashes for strings of lengths $10^5$, you need four hashes of primemodulo around $10^9

Full text and comments »

  • Vote: I like it
  • +367
  • Vote: I do not like it

123.
By Ripatti, 14 years ago, translation, In English
Editorial for Codeforces Round #133 **A.** For solving this problem you might find some formula like $res = abc - (a-1)(b-1)(c-1)$, $res = ab+bc+ca - a-b-c +1$, or something else. Also the problem can be solved in $O(a+b+c)$ time --- you can move from the top line to the bottom line of hexagon and sum number of tiles in every line. Author is ~Ripatti,2012-08-14 . **B.** You can build some graph where vertices are students and edges are enmities. You should drop some vertices and then paint them in two colors. Any edge should connect vertices of distinct colors and numbers of vertices of every color should be same. You can see that graph consists chians, cycles and sepatated vertices. Every of that component can be painted in 2 colors except one case: cycles of odd length. So, you should drop one vertex from every odd cycle. After that you can get odd number of vertices. Then you should drop one more vertex (you can chose any of them). The obtained graph can be easily painted in 2 colors in the required man...
How to find number of substrings of some modulo? You should iterate over all digits of $s$ from the

Full text and comments »

  • Vote: I like it
  • +40
  • Vote: I do not like it

124.
By Valiors, history, 8 years ago, In English
[Tutorial] Chinese Remainder Theorem **#IjustWantContribution** Hello Codeforces. In this post, I would like to introduce some of you to a very popular, yet maybe not fully understood technique called Chinese Remainder Theorem (CRT). I have seen many articles that present CRT in a way that lacks practical competitive programming approach (no info about how to handle overflows, how to implement it effectively, what to do when modulos are not coprime etc.) and derivation of the formulas seem like some sort of guesswork. The purpose of this article is to address this issue. **Problem and solution** You are given two pairs (main goal is to solve it for $t$ pairs) of integers $(a_1, n_1)$, $(a_2, n_2)$. **There is no assumption that $n_1$ and $n_2$ are coprime**. Find an integer $x$ that satisfies $$ \left\{ \begin{array}{c} x \equiv a_1 \pmod {n_1} \\ x \equiv a_2 \pmod {n_2} \end{array} \right. $$ This system of congruences implies that $$ \left\{ \begin{array}{c} x = a_1 + n_1k_1 \\ x = a_2 + n_2k_...
Sometimes you have to do/calculate something modulo some composite number. Then you can factorize

Full text and comments »

  • Vote: I like it
  • +232
  • Vote: I do not like it

125.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 137 English Solutions Although AtCoder seems to be getting back to posting English editorials, I'm continuing to release some myself in case having the extra explanations helps some people. (Sidenote: Some of the provided submissions come from after the contest itself, because I had to leave midway through, before I got the chance to debug my E or write my F.) --- #A &mdash; +-X Just use your language's max function. As $A$ and $B$ are small, we don't need to worry about integer overflow. Runtime: $O(1).$ [Click here for my submission.](https://atcoder.jp/contests/abc137/submissions/6802607) --- #B &mdash; One Clue Let's try to find the minimum and maximum values in the answer. It's fairly easy to see that all integers between them will also be in the set. To find the minimum possible position of a black stone, we place $K$ black stones such that $X$ is at the maximum position. Then, the minimum position will thus be $X-K+1$, as we have $K-1$ black stones to the left of $X$....
Of course, all arithmetic is modulo $P$. Division is represented by multiplication by a modular

Full text and comments »

  • Vote: I like it
  • +34
  • Vote: I do not like it

126.
By Proofy, 15 months ago, In English
[Tutorial] Abstract Proofs of DP Algorithms ## Introduction Most of DP algorithms I studied online, there are some subtleties that I didn't find any proof of. May be they are found somewhere already, but not to my knowledge. I think most people find the things that I'm going to prove here intuitive and need no proof, but for if you're really picky about being uncertain of something if you didn't see a proof (like me), it can bother you. Also, knowing the proofs can sometimes better help the thinking process. The purpose of this blog is to provide examples of proofs of famous DP algorithms to, first show them, and second serve as a general pattern of techniques on how would one prove a DP algorithm. Now, most DP problem involve a set of states $V$, and a set of transitions $E$ such that $(V, E)$ constitutes a directed acyclic graph or DAG (sometimes weighted). Thus, we will continue discussing DP calculations on a DAG. ### Conventions - A graph $G = (V, E)$ is a pair of sets $V$ and $E$ where $E \subseteq ...
modulo $10^9 + 7$.

Full text and comments »

  • Vote: I like it
  • +79
  • Vote: I do not like it

127.
By Asakire, history, 11 months ago, In English
Modulo and Integer arithmetic Recently i went through few modulo and integer arithmetic section from a website I am writing this as recap for myself but it might help beginners who are unfamiliar with Modular arithmetic A few basic observations ======================== If a mod b = 0, then a is divisible by b. This single condition appears in an enormous number of problems, from basic number theory to constraints checking. Another common use is determining parity. `If n mod 2 = 0, the number is even`; `if n mod 2 = 1, it is odd`. Whenever a problem involves alternating behavior, parity, or splitting elements into two groups, modulo 2 is usually the first thing worth checking. Modulo and cyclic behavior ========================== One important property of modulo is that it naturally creates cycles. The values of n mod 5, for instance, repeat as `0, 1, 2, 3, 4, 0, 1, 2, 3, 4, ....` This is extremely useful in practice. Circular arrays, rotating turns, and repeating patterns can all be handl...
Modulo and Integer arithmetic, values. This is crucial when problems ask for answers modulo a large number such as 10^9 + 7, A frequent mistake is confusing division with modulo, or mixing them incorrectly in expressions, Digit extraction using modulo -----------------------------, Integer division and modulo are complementary. Integer division tells us how many full groups can, Integer division vs modulo --------------------------, Modulo and cyclic behavior ==========================, Modulo properties and large numbers ===================================, Negative numbers and modulo --------------------------- modulo with negative numbers, Recently i went through few modulo and integer arithmetic section from a website I am writing, Recently i went through few modulo and integer arithmetic section from a website, Two properties of modulo are used constantly in competitive programming:, consider computing a product of two very large numbers modulo 10^9 + 7. Direct multiplication may

Full text and comments »

  • Vote: I like it
  • -2
  • Vote: I do not like it

128.
By ODT, history, 9 years ago, In English
Codeforces Round #449 Editorial [897A &mdash; Scarborough Fair](http://codeforces.me/contest/897/problem/A) By [user:mcfx,2017-12-04] For every $i$ in range $[l,r]$, if $c_i$ is $c_1$ then change it into $c_2$... Because $n, m$ are all very small, $O( nm )$ can easily pass it. PS. You can use binary search tree to solve it in $O( m\log n )$ time. [897B &mdash; Chtholly's request](http://codeforces.me/contest/897/problem/B) By [user:mcfx,2017-12-04] The $k$-th smallest zcy number is $conn(str(k),rev(str(k)))$, where $str$ denotes the decimal representation of a positive integer as a string, $conn$ denotes the concatenation two strings, and $rev$ denotes the reverse of a string. Then go over the smallest $k$ such numbers and sum them up to obtain the answer. [896A &mdash; Nephren gives a riddle](http://codeforces.me/contest/896/problem/A) By [user:mcfx,2017-12-04] $f(n)=str_1+f(n-1)+str_2+f(n-1)+str_3$. First we can compute the length of $f(n)$ for all possible $n$. For a pair of $(n...
One last question is about the modulo number. First separate it into forms like $(p_1^{a_1})*(p_2

Full text and comments »

  • Vote: I like it
  • +180
  • Vote: I do not like it

129.
By Elegia, history, 23 months ago, In English
More on D-Finite Functions II: Problems After finishing this part, I found out some of them are not that related to D-Finite functions (especially for the last section), but in these problems, we still need some insight to deal with differential operators. So I'll keep them here. ## Sums involving powers Let's consider the following problem of summation $$ \sum_{0\leq n \leq M} f(n) \cdot n^k, $$ where $M$ can be finite or infinite. We want to separate a large class of $f$ such that such summation can be solved in $O(k)$. You may already know some examples: - For the constant function $f(n) = 1$, known as [662F](https://codeforces.me/problemset/problem/622/F), can be solved in linear time through Lagrange interpolation on consecutive sampling points. - For the geometric series $f(n) = r^n$, you can find the [finite case](https://judge.yosupo.jp/problem/sum_of_exponential_times_polynomial) and [infinite case](https://judge.yosupo.jp/problem/sum_of_exponential_times_polynomial_limit) (assume $|r| < 1$) in Libra...
Remark: As we know, there are ways to avoid polynomial modulo operations in multipoint evaluation

Full text and comments »

  • Vote: I like it
  • +113
  • Vote: I do not like it

130.
By Nanako, 4 years ago, In English
Good Bye 2022 -- Editorial ## [problem:1770A] Idea by [user:m_99,2022-12-30] <spoiler summary="Hint 1"> Exactly $n$ items out of of $a_1,\ldots,a_n,b_1,\ldots,b_m$ will remain on the whiteboard at the end. </spoiler> <spoiler summary="Hint 2"> $b_m$ will always remain on the board at the end. </spoiler> <spoiler summary="Hint 3"> Consider the case where $n=2$ and $m=2$. As we mentioned in hint 2, $b_2$ will always be written, but what about $b_1$? </spoiler> </details> <spoiler summary="Solution"> This problem can be solved naturally with a greedy algorithm &mdash; for $i = 1, 2, \dots, m$, we use $b_i$ to replace the minimal value among the current $a_1, a_2, \dots, a_n$. The time complexity is $O(nm)$ for each test case. Alternatively, we can first add $b_m$ to our final sum. For the remaining $(n+m-1)$ integers, we can freely pick $(n - 1)$ out of them and add it to our final sum. This is because if we want a certain $a_i$ to remain on the board at the end, we simply do not touch i...
sum is $x$ and total or is a subset of $y$, modulo $2$ is equal to $\sum_{t_1+\ldots+t_n=x} \prod, That is, if we consider $[5, 6, 7, 8]$ modulo $2$, we obtain the multiset $\{1, 0, 1, 0\}$. Both $0

Full text and comments »

  • Vote: I like it
  • +243
  • Vote: I do not like it

131.
By majk, 8 years ago, In English
Good Bye 2018 Problem G I realised I have too much contribution anyway, so I write this blog about G of today's contest. This problem was plagued by technical issues from start to finish. When you read some of them, you will probably ask yourself how the hell did I get red in the first place. Originally, the problem had $n$ a product of just $2$ primes. We then decided to raise it up to $10$ primes. I was really confused that I had two types of runs &mdash; either they passed with runtime 30ms, or they got TLE or ILE. I added time measurement to the interactor itself, and found out that the 30ms solutions in fact took more than couple seconds to run. The same solutions reported run time of couple seconds in Gym contest that we used for testing. During post contest discussions with [user:MikeMirzayanov,2018-12-30] I realised that I still don't understand how Polygon and Codeforces measure time for interactive problems. I am not the fastest duck in the pond, so I investigated my Tonelli Shanks impleme...
number of operations needed to find a square root modulo a prime and facepalmed. I realised that only

Full text and comments »

  • Vote: I like it
  • +336
  • Vote: I do not like it

132.
By ikrpprppp, 2 years ago, In English
Codeforces Round 961 (Div. 2) Editorial [problem:1995A] --------------- <spoiler summary="Hint"> How many described diagonals are there in total? How many cells do they contain? </spoiler> <spoiler summary="Answer to Hint"> In total we have $2 n - 1$ diagonals. There is only one diagonal that contains $n$ cells, two containing $n - 1$ cells, ..., and two containing only one cell each (namely passing through $(1, n)$ and $(n, 1)$). </spoiler> <spoiler summary="Solution"> Obviously, in this case, it is worth filling the largest diagonal with chips, then two that are smaller in size, and so on. The asymptotics turns out to be $O(n)$. </spoiler> <spoiler summary="Code"> [submission:272176453] </spoiler> [problem:1995B1] ---------------- <spoiler summary="Hint"> For each number of petals, we can bruteforce the answer for $x, x + 1$ </spoiler> <spoiler summary="Solution"> First, we can aggregate number of flowers with $x$ petals into $c_{x}$ (for example, sort the array and then create array of pa...
(All the indices for the desks are taken modulo $n$ and all the indices for the knights are taken

Full text and comments »

  • Vote: I like it
  • +100
  • Vote: I do not like it

133.
By adamant, 10 months ago, In English
Fastest bitwise convolutions Hi everyone! There are 3 roughly similar problems on Library Checker: - **[Bitwise Xor Convolution](https://judge.yosupo.jp/problem/bitwise_xor_convolution)** - **[Bitwise And Convolution](https://judge.yosupo.jp/problem/bitwise_and_convolution)** - **[Subset Convolution](https://judge.yosupo.jp/problem/subset_convolution)** All of them ask us to find $c_0, \dots, c_{2^n-1}$, where $$ c_k = \sum\limits_{i \circ j = k} a_i b_j, $$ where $\circ$ stands for bitwise xor, bitwise and, and "disjoint or" correspondingly. As of now, my submissions are the fastest one for all 3 problems, and in this blog I'd like to explain how it is achieved. XOR / AND convolutions are fairly simple, which is why my **30 ms** submissions are closely followed by others. However, for subset convolution, my submission uses **94 ms** with just **34 MiB**, while all other submissions (except the one by ~Qwerty1232,2026-02-15 on the second place, whose approach is similar to mine) use at least 3...
, and use Montgomery reduction to drop them back to being modulo $M$ in the end. The whole code then

Full text and comments »

  • Vote: I like it
  • +101
  • Vote: I do not like it

134.
By Spheniscine, history, 7 years ago, In English
Modular Arithmetic for Beginners Introduction ------------------ If you're new to the world of competitive programming, you may have noticed that some tasks, typically combinatorial and probability tasks, have this funny habit of asking you to calculate a huge number, then tell you that "because this number can be huge, please output it modulo $10^9 + 7$". Like, it's not enough that they ask you to calculate a number they know will overflow basic integer data types, but now you need to apply the modulo operation after that? Even worse are those that say you need to calculate a fraction $\frac pq$ and ask you to output $r$ where $r \cdot q \equiv p \pmod m$... not only do you have to calculate a fraction with huge numbers, how in the *world* are you going to find $r$? Actually, the modulo is there to make the calculation *easier*, not *harder*. This may sound counterintuitive, but once you know how modular arithmetic works, you'll see why too. Soon you'll be solving these problems like second nature. Terminol...
First off, some important identities about the modulo operator:, Here are some simpler puzzles that require a modulo answer:, The value $m$ after the modulo operator is known as the *modulus*. The result of the expression $n

Full text and comments »

  • Vote: I like it
  • +46
  • Vote: I do not like it

135.
By AlexSkidanov, 13 years ago, In English
MemSQL start[c]up Round 1 editorial **[Square and Rectangles](http://codeforces.me/problemset/problem/325/A)** Author: [user:SkidanovAlex,2013-07-14] What happens if the rectangles form an $N \times N$ square? Then these two conditions are necessary. 1) The area must be exactly $N \times N$. 2) The length of its sides must be $N$. That means, the difference between the right side of the rightmost rectangle &mdash; the left side of the leftmost rectangle is $N$. Same for topmost and bottommost rectangles. We claim that, since the rectangles do not intersect, those two conditions are also sufficient. This is since if there are only $N \times N$ space inside the box bounded by the leftmost, rightmost, topmost, and bottommost rectangles. Thus if the sum of the area is exactly $N \times N$, all space must be filled -- which forms a square. **[Stadium and Games](http://codeforces.me/problemset/problem/325/B)** Author: nika Suppose the "divide-by-two" stage happens exactly $D$ times, and the ...
In this part of editorial, all numbers we speak are in modulo $N$. So, if I say 10, it actually

Full text and comments »

  • Vote: I like it
  • +61
  • Vote: I do not like it

136.
By malcolm, 11 years ago, translation, In English
Editorial Codeforces Round #319 Task A. Div2. It's easy to see that number $x$ can appear in column $i$ only once &mdash; in row $x / i$. For every column $i$, let's check that $x$ divides $i$ and $x / i \le n$. If all requirements are met, we'll update the answer. The complexity is $O(n)$ [Source](http://pastebin.com/yGMTt9KZ) Task B. Div2. Let's consider two cases: $n > m$ and $n \le m$. If $n > m$, let's look at prefix sums. By pigeonhole principle, there are two equals sums modulo $m$. Assume $S_l mod m = S_r mod m$. Then the sum on segment $[l + 1, r]$ equals zero modulo $m$, that means the answer is definitely "YES". If $n \le m$, we'll solve this task using dynamic programming in $O(m^2)$ time. Assume $can[i][r]$ means if we can achieve the sum equal to $r$ modulo $m$ using only first $i - 1$ items. The updates in this dynamic programming are obvious: we either take number $a_i$ and go to the state $can[i + 1][(r + a_i)\ mod\ m]$ or not, then we'll get to the state $can[i + 1][r]$. The ...
If $n > m$, let's look at prefix sums. By pigeonhole principle, there are two equals sumsmodulo $m

Full text and comments »

  • Vote: I like it
  • +87
  • Vote: I do not like it

137.
By Shayan, 20 months ago, In English
Codeforces Round 1011 (Div 2) — Video Tutorial **Note: The text editorials will be provided by the authors of the round. This video tutorial acts as an additional resource for those who prefer video over text, not as a substitute for the text editorial.** ### [2085A &mdash; Serval and String Theory](https://codeforces.me/contest/2085/problem/A) <spoiler summary="Video"> <iframe width="800" height="450" src="https://www.youtube.com/embed/3-qJSKb8z-s?si=7C3fsSj1exVIxQBi&amp;start=340" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </spoiler> ### [2085B &mdash; Serval and Final Mex](https://codeforces.me/contest/2085/problem/B) <spoiler summary="Video"> <iframe width="800" height="450" src="https://www.youtube.com/embed/3-qJSKb8z-s?si=7C3fsSj1exVIxQBi&amp;start=1130" title="YouTube video player" frameborder="0" allow="accelerometer; autop...
### [2085E — Serval and Modulo](https://codeforces.me/contest/2085/problem/E)

Full text and comments »

  • Vote: I like it
  • +31
  • Vote: I do not like it

138.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 146 English Solutions #A &mdash; Can't Wait for Holiday The only approach here is the trivial one--compare the input to each of the possible seven values and print the appropriate answer for each of them. One reasonably fast way to implement this is to create an array $A$ containing the seven inputs, with "SUN" in position zero and "SAT" in position six. Then, we compare $S$ to each value in the array and, upon finding the value $i$ such that $A[i] = S$, we print $7-i$. This is valid because the next Sunday after the day represented by our input would come in position seven. Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc146/submissions/8604159) --- #B &mdash; ROT N Again, the only real solution here is to directly implement the approach given in the problem statement. However, character arithmetic gives us a fairly nice way to do so. For each character in $S$, we can compute the position of the corresponding letter in the alphabet by taking $S[i]$ minus...
working modulo $K$. We can iterate over all prefixes of the array and maintain a map from prefix

Full text and comments »

  • Vote: I like it
  • +90
  • Vote: I do not like it

139.
By Errichto, 5 years ago, In English
Meet in the Middle (Topic Stream) **Meet in the Middle** lecture & problem-solving starts in an hour https://www.twitch.tv/errichto. See the problem list below. I will later update this blog with codes and written explanations. UPD, video recording: https://youtu.be/18sJ3mK173s, some codes from the stream: https://ideone.com/1uScID P1. Knapsack with $n \leq 40$ and values up to $10^9$ https://cses.fi/problemset/task/1628 P2. Given a sequence $a_1, a_2, \ldots, a_n$ ($n \leq 2000$), count increasing subsequences of length 3. P3. 4-SUM, find four values that sum up to the target value https://cses.fi/problemset/task/1642 P4. Find a string with the standard polynomial hash equal to the target value $X$ modulo $10^9+7$. The hash is computed by converting characters a-z into 0-25 and multiplying every character by the next power of 26. Find a solution without just converting $X$ to base $26$. P5. You're given a graph: $n \leq 300$, $m \leq n\cdot(n-1)/2$. Count paths made of 5 nodes. Nodes and edges can be...
sums modulo $M$. https://quera.ir/problemset/olympiad/34090. The two subsequences can have common

Full text and comments »

  • Vote: I like it
  • +242
  • Vote: I do not like it

140.
By Nickolas, 7 years ago, translation, In English
April Fools Day Contest 2020: editorial _This was the most well-attended April Fools Day Contest in the whole history of them: 10343 participants solved at least one problem! It was also fairly well-balanced: while each problem has been solved by at least 200 participants, only 17 of them solved all 8 problems._ ##[problem:1331A] This was the consolation problem of the contest, and still a lot of participants asked me for hints on this problem &mdash; some even before the beginning of the round! If you're still not sure how to solve it, the contest announcement itself promised that the contest is not rated, so the answer is a resolute ``NO'' (case insensitive, quotes for clarity only) :-) ##[problem:1331B] Unusually for this type of contests, the second problem had an actual problem statement! The real task was hidden in it using Steganography 101 &mdash; the first letters of the lines spelled out "TWO FACTORS". [cut] A quick look at the examples confirmed that you needed to factor the given number and print ...
The answer is just the hexadecimal number given in the input taken modulo 2. The problem is

Full text and comments »

  • Vote: I like it
  • +170
  • Vote: I do not like it

141.
By adamant, history, 5 years ago, In English
On linear recurrences and the math behind them Hi everyone! There are already dozens of blogs on linear recurrences, why not make another one? In this article, my main goal is to highlight the possible approaches to solving linear recurrence relations, their applications and implications. I will try to derive the results with different approaches independently from each other, but will also highlight similarities between them after they're derived. ### Definitions **Def. 1**. An order $d$ **homogeneous linear recurrence with constant coefficients** (or _linear recurrence_) is an equation of the form $$ F_n = \sum\limits_{k=1}^d a_k F_{n-k}. $$ **Def. 2**. In the equation above, the coefficients $a_1, \dots, a_d \in R$ are called the **recurrence parameters**, **Def. 3**. and a sequence $F_0, F_1, \dots \in R$ is called an order $d$ **linear recurrence sequence**. <hr> The most common task with linear recurrences is, given initial coefficients $F_0, F_1, \dots, F_{d-1}$, to find the value of $F_n$. <hr> **Example...
calculating it modulo $A(b)$. If, after that, we do a back-substitution of $F_k$ instead of $b^k$, we

Full text and comments »

  • Vote: I like it
  • +266
  • Vote: I do not like it

142.
By riadwaw, 11 years ago, translation, In English
AIM Tech Round Tutorial [problem:624A] Width of free space is decreasing by $v_1 + v_2$ per second. It means that it'll decrease from $L$ to $d$ in $t = \frac{L - d}{v_1 + v_2}$ seconds. The moment when width gets a value of $d$ is the last when Luke is alive so $t$ is the answer. [problem:624B] Sort array in descending order. Iterate over all letters, First letter is added $c_1 = a_1$ times, each other letter is added $c_i = min(a_i, c_{i - 1})$. Don't forget that if some letter is not added at all, then all next letters are not added too. [problem:623A] Note that all vertices "b" are connected with all other vertices in the graph. Find all such vertices and mark them as "b". Now we need to find any unlabeled vertex $V$, mark it with "a" character. Unlabeled vertices connected with $V$ should be also labeled as "a". All other vertices we can label as "c" Finally we need to check graph validity. Check that all vertices "a" are only connected with each other and "b" vertices. After that we...
We decided to ask the answer modulo $10^9 + 7$ to not let the participants easily guess that these

Full text and comments »

  • Vote: I like it
  • +92
  • Vote: I do not like it

143.
By skywalkert, history, 5 years ago, In English
2019 Summer PtzCamp, Day 8: XIX Open Cup Onsite, Editorial This editorial corresponds to [contest:103652], a.k.a "Jingzhe Tang Contest 2", held on Sept. 1st, 2019. Moreover, this problem set is a selection of "CCPC-Wannafly Winter Camp 2018, Day 2 (Div. 1 & Div. 2)" held on Jan 30th, 2019. Feel free to comment on the tutorials listed in the following (with some follow-up questions left to readers). Hope you enjoy solving these problems. --- [problem:103652A] <spoiler summary="solution"> The number of updates can be counted as the number of ordered pairs $(u, v)$ such that when $u$ is going to be removed, there exists at least one path between $u$ and $v$. If the path between $u$ and $v$ is unique in the original graph, we can conclude that pair exists if $u$ is the first removed node on the path with respect to an order, and $\frac{1}{cnt(u, v)}$ of all possible orders would meet this condition, where $cnt(u, v)$ is the number of nodes on the unique path between $u$ and $v$ (inclusive). In other cases, there exist exactly tw...
The number of solutions $x$ in modulo $2^{k + 2} \cdot 5^k$ for the equation $x^2 \equiv y$ is the

Full text and comments »

  • Vote: I like it
  • +92
  • Vote: I do not like it

144.
By jeroenodb, history, 6 years ago, In English
Cool problem about persistence Hey codeforces, I found an old blog about an interesting problem about persistent lists: [Old blog](https://codeforces.me/blog/entry/51136?) [Problem and submit on e-olymp](https://www.e-olymp.com/en/problems/2957) In this problem you start with a bunch of lists of integers (all with length 1 at the start). There are three operations: - merge i j: Make a brand new list that is the concatenation of list i and list j. (i and j could be the same) - head i: Make two new lists: One with the first element (the head) of list i and one with all the other values - tail i: Make two new lists: One with all the elements except the last, and one with all the other values. After each operation you have to report the sum of numbers in all the newly created lists modulo $10^9 + 7$. Constraints are: number of starting lists with one number inside $\leq 10^5$ and number of operations $\leq 10^5$ The difficulty of this problem lies in the fact that with the operation merge, ...
After each operation you have to report the sum of numbers in all the newly created listsmodulo

Full text and comments »

  • Vote: I like it
  • +21
  • Vote: I do not like it

145.
By PrinceOfPersia, history, 10 years ago, In English
Codeforces Round #362 (Editorial) [Here](https://gitlab.com/amirmd76/cf-round-362/tree/master) is git repository to solutions of problems of this contest. ### Div.2 A You should check two cases for YES: 1. $x\ mod\ s = t\ mod\ s$ and $t \leq x$ 2. $x\ mod\ s = (t + 1)\ mod\ s$ and $t+1 < x$ ![ ](http://espresso.codeforces.com/72731d179aee0e03fb8a446ab4bb2d2c333953b9.png) Time Complexity: $\mathcal O(1)$ [Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/2A) ### Div.2 B Nothing special, right? just find the position of letters `.` and `e` with string searching methods (like `.find`) and do the rest. ![ ](http://espresso.codeforces.com/67436d52032041dc54647c27e506f956e344f5cb.png) Time Complexity: $\mathcal O(n)$ [Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/2B) ### A Do what problem wants from you. The only thing is to find the path between the two vertices (or LCA) in the tree. You can do this in $\mathcal O(lg(n))$ since the height of the tree is...
(In other words it's modulo $n$ for 1-based)

Full text and comments »

  • Vote: I like it
  • +80
  • Vote: I do not like it

146.
By OtterZ, history, 11 months ago, In English
Border Theory:There's a fast approach to bruteforce on borders UPD:Thanks to comment from [user:arvindf232,2025-12-20] and [user:pajenegod,2025-12-20],I rewrote parts of this post to improve clarity with the help of Chatgpt. I hope it reads more smoothly now. # Preface In this blog, I want to share Border Theory, a useful and elegant insight about string borders that often appears in competitive programming. Although this idea deserves to be as well-known as the KMP algorithm, many people today aren’t aware of it or how to use it to speed up their solutions. # Main Theoretical Result of Border Theory ## Main Result For a string $S$, a border is a substring that is both a prefix of $S$ and a suffix of $S$. For a string $S$, we define that: $$ \{b_i\}_{i=1}^n$$ is the sequence of all lengths of the border of $S$, sorted in increasing order. According to the theory,it's garenteed that for all possible $S$, ${B_i}_{i = 1}^n$ can be partitioned into $\operatorname{O}(\log |S|)$ continuous subsequences where each subsequence f...
modulo $x$, Each allowed addition corresponds to a directed edge between nodes. Our goal is to run a

Full text and comments »

  • Vote: I like it
  • +129
  • Vote: I do not like it

147.
By wilcot, 3 years ago, translation, In English
Discrete square root modulo Just recently I had a need to solve the following problem: Given $a$ and $m$, find all $x$ such that: $x^2 \equiv a \pmod{m}$. After some time searching the Internet and carefully analyzing each case, I got a solution that works for any $a$ and $m > 0$ in $O(\sqrt{m})$ time, or in $O(\log^2(m))$ time if $a$ and $m$ are coprime (if there is a factorization of $m$). Below are the cases I considered and links to articles (or discussions) for algorithms: 1. $x^2 \equiv a \pmod{p}$, $a \ne 0$, $p$ &mdash; odd prime ([link](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm#The_algorithm)). 2. $x^2 \equiv a \pmod{p^k}$, $a \ne 0$, $k > 0$, $\gcd(a, p) = 1$, $p$ &mdash; odd prime ([link](https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm#Tonelli's_algorithm_will_work_on_mod_p^k)). 3. $x^2 \equiv a \pmod{2^k}$, $a \ne 0$, $k > 0$, $\gcd(a, 2) = 1$ ([link](https://projecteuler.chat/viewtopic.php?t=3506)). 4. $x^2 \equiv 0 \pmod{p^k}$, $k > 0$, $p$ &mdash...
Discrete square root modulo

Full text and comments »

  • Vote: I like it
  • +102
  • Vote: I do not like it

148.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 136 English Solutions #A &mdash; Transfer First, we compute the resulting amount of water in Cup 1. Observe that this is equal to $min(A, B+C)$. Let this value be $D$. Then, the amount transferred from Cup 2 to Cup 1 is simply $D - A$, so the amount remaining in Cup 2 is $C - D + A$. Time complexity: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc136/submissions/6682058) --- #B &mdash; Uneven Numbers There are several efficient ways to approach this problem. One is to simply to count the one-, three-, and five-digit numbers less than or equal to $N$. However, because of the small maximum on $N$, a more naive approach works. Simply iterate over every value from $1$ to $N$, count its digits, and add one to the answer if the count is odd. (We can count a number's digits by repeatedly adding one to the count and dividing the number by ten until it reaches zero.) Time complexity: $O(N \log N)$. Note that $O(\log N)$ is possible with the more efficient approach. ...
modulo $F$. We'll need to decrease some of the values in the multiset and increase others so that all

Full text and comments »

  • Vote: I like it
  • +139
  • Vote: I do not like it

149.
By ksun48, history, 11 years ago, In English
Editorial for CROC 2016 Elimination Round [problem:645A] --- **Idea:** [user:yummy,2016-03-18] One solution is to just brute force and use DFS to try all the possibilities. Alternatively, note that two puzzles can be changed to each other if and only if the $A$, $B$, and $C$ have the same orientation—clockwise or counterclockwise—in the puzzle. A third option, since the number of possibilities is so small, is to simply classify all of the $4!=24$ configurations by hand. <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; string b, b1, b2, e, e1, e2; int main(){ cin >> b1 >> b2 >> e1 >> e2; swap(b2[0], b2[1]); swap(e2[0], e2[1]); b = b1 + b2; e = e1 + e2; b.erase(b.find('X'), 1); e.erase(e.find('X'), 1); if((b + b).find(e) != string::npos){ cout << "YESn"; } else { cout << "NOn"; } } ~~~~~ </spoiler> [problem:645B] --- **Idea: [user:ksun48,2016-03-18]** Loosely speaking, we’re trying t...
$a[j]$. But how do we know which $a[j]$ is minimal while maintaining their valuesmodulo $10^9 + 7$?

Full text and comments »

  • Vote: I like it
  • +89
  • Vote: I do not like it

150.
By BledDest, 12 months ago, In English
About ER185, problem D Judging by the comments in the ER announcement, people seriously disliked problem D (to say the least). I want to explain why it exists. But first, I have to admit that I made two serious mistakes when setting the problem. My first mistake is actually putting it into a 2-hour solo round; in its current state, it is much more suitable for a longer contest with a team of three people, where you can actually get some help in debugging the code or verifying your solution logic. The second mistake will be explained a bit later, but I want to say that I understand why people think this is a terrible problem. I am sorry if this problem made the contest much worse for you. However, I am also asking that you consider my point of view. You don't have to agree with it, but I don't want anyone to view me as some insane author who's setting a problem just to watch everyone get furious while implementing it. This is definitely an implementation-heavy problem. But I think that implementation...
pairs we can have), and the number of changes of the second type is its length modulo $2$ (because

Full text and comments »

  • Vote: I like it
  • +181
  • Vote: I do not like it

151.
By adamant, history, 4 years ago, In English
Permutation group basis construction (Schreier–Sims algorithm) Hi everyone! I had this blog drafter for quite a while, but the [$300 contest](https://codeforces.me/blog/entry/110840) motivated me to actually finish and publish it. I don't care about the prize that much as I think many other blogs published recently are talking about something even cooler. But I like to make people suffer, so I will apply anyway to make [user:peltorator,2023-01-12] read even more stuff >:) Besides, the contest makes it harder to stay on contribution top, so I got to do something to stay afloat. That being said... <hr> Today I'd like to write about an algorithm that solves the following problem: You're given a set of permutations $G = \\{g_1, \dots, g_m\\}$. Find the size $|\langle g_1, \dots, g_m \rangle|$ of the group generated by $G$. At first, I wanted to get into a lot of group-theoretic details with proofs and all, but then I felt like it would make the article harder to comprehend, so I will try to keep group-theoretic stuff to minimum, whi...
/Howell_normal_form) for vectors over remainders modulo possibly composite number $m$ (see e.g. [the

Full text and comments »

  • Vote: I like it
  • +226
  • Vote: I do not like it

152.
By Shayan, 2 years ago, In English
Codeforces Round 991 (Div 3) — Video Tutorial **Note: The text editorials will be provided by the authors of the round. This video tutorial acts as an additional resource for those who prefer video over text, not as a substitute for the text editorial.** ### [2050A &mdash; Line Breaks](https://codeforces.me/contest/2050/problem/A) <spoiler summary="Video"> <iframe width="800" height="450" src="https://www.youtube.com/embed/svlEFTXQKDk?si=jcZOA1U80QNOKQb5&amp;start=191" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </spoiler> ### [2050B &mdash; Transfusion](https://codeforces.me/contest/2050/problem/B) <spoiler summary="Video"> <iframe width="800" height="450" src="https://www.youtube.com/embed/svlEFTXQKDk?si=jcZOA1U80QNOKQb5&amp;start=444" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; e...
### [2050F — Maximum modulo equality](https://codeforces.me/contest/2050/problem/F)

Full text and comments »

  • Vote: I like it
  • +18
  • Vote: I do not like it

153.
By Sammarize, 11 years ago, translation, In English
Codeforces Round 313 — Extended editoral [problem:560A] If there is a banlnot of value 1 then one can to express every sum of money. Otherwise one can't to express 1 and it is minimum unfortunate sum. [problem:560B] It is easy to see that one can snuggle paintings to each other and to edge of board. For instance one can put one of painting right over other. Then height of two paintings equals to sum of two heights and width of two paintings is equals to maximum of two widths. Now we can just iterate orientation of paintings and board. [problem:559A] & [problem:560C] Let's consider regular triangle with sides of $k$ Let's split it to regular triangles with sides of $1$ by lines parallel to the sides. Big triange area $k^2$ times larger then small triangles area and therefore big triangle have splitted by $k^2$ small triangles. If we join regular triangles to sides $a_1, a_3$ and $a_5$ of hexagon we get a triangle sides of $a_1 + a_2 + a_3$. Then hexagon area is equals to $(a_1 + a_2 + a_3)^2 - a_1^2 - a_3^2 -...
modulo $10^9+7$ for calculating binomial coefficients.

Full text and comments »

  • Vote: I like it
  • +97
  • Vote: I do not like it

154.
By LorentzianExpanders, history, 21 month(s) ago, In English
Modulo Inversion in Constant Time, with Subpolynomial Precomputation Hi everyone, In this post, I'll share a method to compute modular inverses in $O(1)$ time under some $p^{\varepsilon}$-time precomputation. Rather than simply computing the modular inverse, we aim to solve for a pair of integers $x, y$ such that $ax + by = \gcd(a, b)$. I.e., find the solution of the Bezout equation. #### Observations > **Observation.** For two non-zero positive integers $a, b$ less than some bound $X$, there exists an invertible integer matrix $M \in \mathrm{GL}_2(\mathbb{Z})$ such that one component of the vector $M \begin{pmatrix}a\\\\b \end{pmatrix}$ is bounded by $X^{1/2}$, and the absolute values of the elements in $M$ are also bounded by $X^{1/2}$. _Proof._ The pigeonhole principle is sufficient to prove this observation. However, there could be a more algorithmic proof by analyzing the execution of Euclid's algorithm. We omit the details of this proof here. $\square$ > **Corollary.** Given two non-zero positive integers $a, b$ less than $X$, an...
Modulo Inversion in Constant Time, with Subpolynomial Precomputation

Full text and comments »

  • Vote: I like it
  • +116
  • Vote: I do not like it