# Modular Arithmetic

第二章也做完咯~

看到这章的标题就感觉要寄。

进去一看果然，全是数学。。（数学废物笑不出来

做了近两天，我只能说数学博大精深，做数学题真的会谢。。

交完最后一题的 flag 觉得整个人都放松下来了，然后就感觉精疲力尽。

做的很艰难，尤其 python 用的还是那么不利索。

由于有些题的代码是通过推导之后直接通过数学定理化简，所以代码很简单。

## Greatest Common Divisor

### Description

The Greatest Common Divisor (GCD), sometimes known as the highest common factor, is the largest number which divides two positive integers (a,b).

For `a = 12, b = 8`

we can calculate the divisors of a: `{1,2,3,4,6,12}`

and the divisors of b: `{1,2,4,8}`

. Comparing these two, we see that `gcd(a,b) = 4`

.

Now imagine we take `a = 11, b = 17`

. Both `a`

and `b`

are prime numbers. As a prime number has only itself and `1`

as divisors, `gcd(a,b) = 1`

.

We say that for any two integers `a,b`

, if `gcd(a,b) = 1`

then `a`

and `b`

are coprime integers.

If `a`

and `b`

are prime, they are also coprime. If `a`

is prime and `b < a`

then `a`

and `b`

are coprime.

Think about the case for

`a`

prime and`b > a`

, why are these not necessarily coprime?

There are many tools to calculate the GCD of two integers, but for this task we recommend looking up Euclid’s Algorithm.

Try coding it up; it’s only a couple of lines. Use `a = 12, b = 8`

to test it.

Now calculate `gcd(a,b)`

for `a = 66528, b = 52920`

and enter it below.

### Analyze

就是算最大公约数啦，简单写个函数就好咯。

现在再看这题是真简单啊。

### Code

def gcd(a: int, b: int) -> int: |

### SumUp

# 欧几里得算法，是 C 语言做过的东西 |

## Extended GCD

### Description

Let `a`

and `b`

be positive integers.

The extended Euclidean algorithm is an efficient way to find integers `u,v`

such that

a * u + b * v = gcd(a,b) |

Later, when we learn to decrypt RSA, we will need this algorithm to calculate the modular inverse of the public exponent.

Using the two primes `p = 26513, q = 32321`

, find the integers `u,v`

such that

p * u + q * v = gcd(p,q) |

Enter whichever of `u`

and `v`

is the lower number as the flag.

Knowing that

`p,q`

are prime, what would you expect`gcd(p,q)`

to be? For more details on the extended Euclidean algorithm, check out this page.

### Analyze

用到扩展的欧几里得算法，数学原理和辗转相除大同小异，简单代下数字手推一遍详细过程就知道怎么回事咯。

### Code

def exgcd(a: int, b: int) -> (int, int, int): |

### SumUp

# 扩展欧几里得，不限制输入的大小顺序 |

## Modular Arithmetic 1

### Description

Imagine you lean over and look at a cryptographer’s notebook. You see some notes in the margin:

4 + 9 = 1 |

At first you might think they’ve gone mad. Maybe this is why there are so many data leaks nowadays you’d think, but this is nothing more than modular arithmetic modulo 12 (albeit with some sloppy notation).

You may not have been calling it modular arithmetic, but you’ve been doing these kinds of calculations since you learnt to tell the time (look again at those equations and think about adding hours).

Formally, “calculating time” is described by the theory of congruences. We say that two integers are congruent modulo m if `a ≡ b mod m`

.

Another way of saying this, is that when we divide the integer `a`

by `m`

, the remainder is `b`

. This tells you that if m divides a (this can be written as `m | a`

) then `a ≡ 0 mod m`

.

Calculate the following integers:

11 ≡ x mod 6 |

The solution is the smaller of the two integers.

### Analyze

模运算来了，头大。后面全是和模运算有关的（准确来说这一整章都是

这道算简单，取余算一下 x 和 y，然后按要求输出小的。没啥好思考的捏。

### Code

n = 8146798528947 |

## Modular Arithmetic 2

### Description

We’ll pick up from the last challenge and imagine we’ve picked a modulus `p`

, and we will restrict ourselves to the case when `p`

is prime.

The integers modulo `p`

define a field, denoted `Fp`

.

If the modulus is not prime, the set of integers modulo

`n`

define a ring.

A finite field `Fp`

is the set of integers `{0,1,...,p-1}`

, and under both addition and multiplication there is an inverse element `b`

for every element `a`

in the set, such that `a + b = 0`

and `a * b = 1`

.

Note that the identity element for addition and multiplication is different! This is because the identity when acted with the operator should do nothing:

`a + 0 = a`

and`a * 1 = a`

.

Lets say we pick `p = 17`

. Calculate `317 mod 17`

. Now do the same but with `517 mod 17`

.

What would you expect to get for `716 mod 17`

? Try calculating that.

This interesting fact is known as Fermat’s little theorem. We’ll be needing this (and its generalisations) when we look at RSA cryptography.

Now take the prime `p = 65537`

. Calculate `27324678765465536 mod 65537`

.

Did you need a calculator?

### Analyze

费马小定理，蛮有意思的一个公式。

$a^{p} \equiv a \mod p$，浅浅变形一下：$a^{p-1} \equiv 1 \mod p$

主要题目描述这个定理的时候略微有一点写复杂咯，不够优雅（ bushi。

这么推导出来其实没有写代码的必要。

### Code

a = 273246787654 |

## Modular Inverting

### Description

As we’ve seen, we can work within a finite field `Fp`

, adding and multiplying elements, and always obtain another element of the field.

For all elements `g`

in the field, there exists a unique integer `d`

such that `g * d ≡ 1 mod p`

.

This is the multiplicative inverse of `g`

.

**Example**: `7 * 8 = 56 ≡ 1 mod 11`

What is the inverse element: `3 * d ≡ 1 mod 13`

?

Think about the little theorem we just worked with. How does this help you find the inverse of an element?

### Analyze

模逆运算，同余这块的知识。主要是欧拉定理和费马小定理的应用。

欧拉定理：$a^{φ(n)} \equiv 1 \mod n$

费马小定理：$a^{p-1} \equiv 1 \mod p$

对于这道题，有 $3 * d \equiv 1 \mod 13$

因为 gcd(3, 13) = 1，所以可以直接得

python 的 pow() 函数真的很好用！

### Code

d = pow (3, 11, 13) |

### SumUp

$φ(n)$ 即 `1 ~ (n-1)`

范围内与 n 互素的数的个数，若 n 本身为素数，则 $φ(n)=n-1$ 。

## Quadratic Residues

### Description

We’ve looked at multiplication and division in modular arithmetic, but what does it mean to take the square root modulo an integer?

For the following discussion, let’s work modulo `p = 29`

. We can take the integer `a = 11`

and calculate `a² = 5 mod 29`

.

As `a = 11, a² = 5`

, we say the square root of `5`

is `11`

.

This feels good, but now let’s think about the square root of `18`

. From the above, we know we need to find some integer `a`

such that `a² = 18`

Your first idea might be to start with `a = 1`

and loop to `a = p-1`

. In this discussion `p`

isn’t too large and we can quickly look.

Have a go, try coding this and see what you find. If you’ve coded it right, you’ll find that for all `a ∈ Fp*`

you never find an `a`

such that `a² = 18`

.

What we are seeing, is that for the elements of `F*p`

, not every element has a square root. In fact, what we find is that for roughly one half of the elements of `Fp*`

, there is no square root.

We say that an integer

`x`

is aQuadratic Residueif there exists an`a`

such that`a² = x mod p`

. If there is no such solution, then the integer is aQuadratic Non-Residue.

In other words, `x`

is a quadratic residue when it is possible to take the square root of `x`

modulo an integer `p`

.

In the below list there are two non-quadratic residues and one quadratic residue.

Find the quadratic residue and then calculate its square root. Of the two possible roots, submit the smaller one as the flag.

If

`a² = x`

then (-a)² = x. So if`x`

is a quadratic residue in some finite field, then there are always two solutions for`a`

.

p = 29 |

### Analyze

Legendre 符号（欧拉判别法）的内容，二次剩余。

定义：如果 $a^2 \equiv x \mod p$ 有解，则 x 是模 p 的二次剩余，否则称为二次非剩余,。

Given: p, x[]

Asked: 找出二次剩余，并求出平方根。

遍历 x in range(1, p)，计算 x 的平方模 p，并与 ints[] 中的元素进行比较，找出模 p 的二次剩余，此时的 x 即为该二次剩余的平方根。

公式和题里的 a 和 x 参数真的很容易弄混，理了半天才理清楚 。。

### Code

p = 29 |

## Legendre Symbol

### Description

In Quadratic Residues we learnt what it means to take the square root modulo an integer. We also saw that taking a root isn’t always possible.

In the previous case when `p = 29`

, even the simplest method of calculating the square root was fast enough, but as `p`

gets larger, this method becomes wildly unreasonable.

Lucky for us, we have a way to check whether an integer is a quadratic residue with a single calculation thanks to Legendre. In the following, we will assume we are working modulo a prime `p`

.

Before looking at Legendre’s symbol, let’s take a brief detour to see an interesting property of quadratic (non-)residues.

Quadratic Residue * Quadratic Residue = Quadratic Residue |

Want an easy way to remember this? Replace “Quadratic Residue” with

`+1`

and “Quadratic Non-residue” with`-1`

, all three results are the same!

So what’s the trick? The Legendre Symbol gives an efficient way to determine whether an integer is a quadratic residue modulo an odd prime `p`

.

Legendre’s Symbol: `(a / p) ≡ a(p-1)/2 mod p`

obeys:

(a / p) = 1 if a is a quadratic residue and a ≢ 0 mod p |

Which means given any integer `a`

, calculating `pow(a,(p-1)/2,p)`

is enough to determine if `a`

is a quadratic residue.

Now for the flag. Given the following 1024 bit prime and 10 integers, find the quadratic residue and then calculate its square root; the square root is your flag. Of the two possible roots, submit the larger one as your answer.

So Legendre’s symbol tells us which integer is a quadratic residue, but how do we find the square root?! The prime supplied obeys

`p = 3 mod 4`

, which allows us easily compute the square root. The answer is online, but you can figure it out yourself if you think about Fermat’s little theorem.

### Analyze

Legendre 符号的欧拉判别法。

欧拉判别法内容：$(a/p) \equiv a^{(p-1)/2} \mod p$。

遍历 ints 判断各自对应的 $(a/p)$ 是否等于 1，得到二次剩余 a 之后计算平方根 $a^{(p+1)/4} \mod p$ 。

### Code

p = 101524035174539890485408575671085261788758965189060164484385690801466167356667036677932998889725476582421738788500738738503134356158197247473850273565349249573867251280253564698939768700489401960767007716413932851838937641880157263936985954881657889497583485535527613578457628399173971810541670838543309159139 |

## Modular Square Root

### Description

In Legendre Symbol we introduced a fast way to determine whether a number is a square root modulo a prime. We can go further: there are algorithms for efficiently calculating such roots. The best one in practice is called Tonelli-Shanks, which gets its funny name from the fact that it was first described by an Italian in the 19th century and rediscovered independently by Daniel Shanks in the 1970s.

All primes that aren’t 2 are of the form `p ≡ 1 mod 4`

or `p ≡ 3 mod 4`

, since all odd numbers obey these congruences. As the previous challenge hinted, in the `p ≡ 3 mod 4`

case, a really simple formula for computing square roots can be derived directly from Fermat’s little theorem. That leaves us still with the `p ≡ 1 mod 4`

case, so a more general algorithm is required.

In a congruence of the form `r² ≡ a mod p`

, Tonelli-Shanks calculates `r`

.

Tonelli-Shanks doesn’t work for composite (non-prime) moduli. Finding square roots modulo composites is computationally equivalent to integer factorization.

The main use-case for this algorithm is finding elliptic curve co-ordinates. Its operation is somewhat complex so we’re not going to discuss the details, however, implementations are easy to find and Sage has one built-in.

Find the square root of `a`

modulo the 2048-bit prime `p`

. Give the smaller of the two roots as your answer.

### Analyze

sympy 模块内有封装好的函数可以计算二次剩余。

函数 nthroot_mod(a, n, p) 用于求解于 $x^{n} \equiv a\ mod\ p$ 的同余式。

题目给了表达式 $r^2 \equiv a\ mod\ p$，求 r。

写了半天函数心态爆炸，然后搜了下 python 相关的库，几行就解决。

再次感叹，python 真是个好东西。

### Code

import sympy |

### SumUp

$x^{n} \equiv a\ mod\ p$，求 x

# function: |

## Chinese Remainder Theorem

### Description

The Chinese Remainder Theorem gives a unique solution to a set of linear congruences if their moduli are coprime.

This means, that given a set of arbitrary integers `ai`

, and pairwise coprime integers `ni`

, such that the following linear congruences hold:

Note “pairwise coprime integers” means that if we have a set of integers

`{n1, n2, ..., ni}`

, all pairs of integers selected from the set are coprime:`gcd(ni, nj) = 1`

.

x ≡ a1 mod n1 |

There is a unique solution `x ≡ a mod N`

where `N = n1 * n2 * ... * nn`

.

In cryptography, we commonly use the Chinese Remainder Theorem to help us reduce a problem of very large integers into a set of several, easier problems.

Given the following set of linear congruences:

x ≡ 2 mod 5 |

Find the integer `a`

such that `x ≡ a mod 935`

Starting with the congruence with the largest modulus, use that for

`x ≡ a mod p`

we can write`x = a + k*p`

for arbitrary integer`k`

.

### Analyze

中国剩余定理，也叫孙子定理。主要针对同余方程组的求解问题。

YouTube 上找了个视频看了原理，跟着视频手算出来了结果，感觉跟着例题一步步算真的能加深理解诶，很容易就理解到了原理和用法。

算法直接找了个板子，偷个懒捏。

### Code

from functools import reduce |

## Adrien’s Signs

### Description

Adrien’s been looking at ways to encrypt his messages with the help of symbols and minus signs. Can you find a way to recover the flag?

### Analyze

python 学得不好，加密函数理解了好久。

解密倒还好，拿到密文直接正常取对数，取不到就负数取余把 n 还原回去再取对数。

不过代码得跑一会才能出结果，后面或许可以再看看有没有更优解。

（最后一行的代码简直写得太优雅咯

### Code

from numpy import arange |

## Modular Binomials

### Description

Rearrange the following equations to get `p,q`

N = p*q |

### Analyze

给了五个参数，求两个未知数 p 和 q，一眼看到给了 p，q 的乘积 N，所以只要随便求出来其中一个然后除 N 就可以咯。

我是先求了 q，所以先把两个方程右边配成齐次的，然后把要消掉的 p 的系数配成一样的，q 的系数刚好是 15 和 14，相减就是 q 咯。

最后一道题倒是没啥技术含量，就嗯解方程组。

### Code

import math |