# ICM2001 - Editorial (Yet Another Mod Mod Mod)

**URL:** <https://discuss.codechef.com/t/icm2001-editorial-yet-another-mod-mod-mod/53608>\
**Category:** editorial\
**Tags:** bitset, icm, math, medium-hard\
**Created:** [February 17, 2020, 1:58pm UTC](https://discuss.codechef.com/t/icm2001-editorial-yet-another-mod-mod-mod/53608 "2020-02-17T13:58:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![theanshul](https://discuss.codechef.com/user_avatar/discuss.codechef.com/theanshul/32/24644_2.png) [@theanshul](https://discuss.codechef.com/u/theanshul)\
**Post date:** [February 17, 2020, 1:58pm UTC](https://discuss.codechef.com/t/icm2001-editorial-yet-another-mod-mod-mod/53608/1 "2020-02-17T13:58:52Z")

</div>

[practice](https://www.codechef.com/problems/ICM2001)  
[contest](https://www.codechef.com/ICM2020/problems/ICM2001)

**Author** : [Anshul Asawa](https://www.codechef.com/users/theanshul)  
**Tester** : [Jatin Yadav](https://www.codechef.com/users/jtnydv25)

# DIFFICULTY:

MEDIUM-HARD

# PREREQUISITES:

Basic Math

# PROBLEM:

You are given n numbers a\_1,a\_2, ... a\_n and another number x. Let P= p\_1,p\_2,...p\_n be any permutation of 1,2,...n.  
Your task is to find the number of distinct values of ((((x\%a\_{p\_1})\%a\_{p\_2})\%a\_{p\_3}...)\%a\_{p\_n}

# EXPLANATION:

We reduce to the following problem: Given an integer v and set S of values in the range [0, N - 1] represented as a bitset. Find the set of values y \% v for all y in S.

It is equivalent to find a set T of non-negative values t = y - k\*v , k \geq 0 for y in S and choose the values in the range [0, v - 1] from it.

Say we have found a bitset of values y - k \* v, where 0 \leq k \lt 2^r and say this bitset is S\_r. Initially, r = 0 and S\_0 = S.

Then, we can find the bitset S\_{r + 1} = S\_r | (S\_r \>\> (2^r \* v)). [We currently had shift as 0\*v, 1\*v, ... (2^r - 1) \* v, and we can add 2^r \* v to these to get the shifts 0\*v, 1\*v, ..., (2^(r+1)-1)\*v]

Clearly, S\_{log(N/v)} = T, because at r = log(N / v), we would have generated shifts for all possible valid k.

Let Z be the bitset of values 0 \leq p \lt v. Z can be maintained as we iterate on v in decreasing order in O(1) per v.

In the end we replace S by S | (T \& Z) , as we only need to consider values \lt v from the set T.

# Time Complexity:

An easy way to explain the complexity is: A \>\> 2^r \* v is done at max N / 2^r times. Summing over r, total number of shifts done \leq N.

# SOLUTION:

[link](https://www.codechef.com/viewsolution/29780209)
