Modulus of common algorithm formulas

foreword

Today, let's briefly sort out some of the mathematical formulas we commonly use and their application in our algorithms.
For example, we sometimes find factorials and sum N items, then at this time, we can use the quick method, or directly use mathematical formulas such as infinite series, etc., to get the results directly.

Find the greatest common divisor (Euclidean algorithm)

We don't care how it came from, we only need to know that m, n has such a property to find the common divisor.
The common divisors between them can take the remainder of each other, and the value is 0.

The code template is as follows (java code is given here)

public static int gcd(int m,int n){
    
    
	return n==0?m:gcd(n,m%n);
	}

For example, our more classic question
insert image description here
asks that this straight line segment can be divided into several segments. Isn't this the problem of finding the greatest common divisor? The abscissa and the ordinate can be divided into several parts at the same time. Isn't this just about finding the common divisor in disguise. (Don't ask why it's not the smallest, just ask is 1)

Bezu's equation

Speaking of this, let's first talk about what this thing does.

A system of equations ax+by = d
find the solution of x, y. And d is the greatest common divisor of ab. Obviously x, y has infinitely many solution sets.

First of all, we have a rule, we only need to find one of the solutions to find all the solutions.
For example

12x + 42y = 6

4,-1 is one of the solutions. So what are the other solutions?
Obviously, we can find that
4+(±)(42/6) and 1+(±)(12/6)
are another set of solutions. As long as this goes on, there are infinite solutions.

So how do you find the first set of solutions when the problem occurs.

Here is the recursive formula

x = y1
y = x1 -a/b * y1

This x1, y1 is after the second step operation

public class 贝祖公式 {
    
    
    static long x;
    static long y;

    static long gcd(long m,long n){
    
    
        return n==0?m:gcd(n,m%n);
    }

    static long lcm(long a,long b){
    
    
        //求最小公倍数
        return a*b /gcd(a,b);
    }

    static long beizu(long a,long b){
    
    
        if(b==0){
    
    
            x = 1;
            y = 0;
            return a;
        }
        long res = beizu(b,a%b);
        long x1 = x;
        x = y;
        y = x1-a/b*y;
        return res;
    }
    static long linefunction(long a,long b,long m) throws Exception{
    
    
        long d = beizu(a,b);
        if(m%d!=0) throw new Exception("无解");
        long n = m/d;
        x *=n;
        y *=n;
        return d;
    }
}

class 贝祖test{
    
    
    public static void main(String[] args) throws Exception {
    
    
        贝祖公式.linefunction(12,42,6);
        System.out.println("x:"+贝祖公式.x+" "+"y:"+ 贝祖公式.y);
    }
}

After you get the code, you can adjust it yourself. If you can't understand it, just memorize it and know how to use it.

Blue Bridge Cup: one step away

The topics are as follows:

This question is a fill-in-the-blank question. After calculating the result, use the output statement in the code to output the filled result.

Awakening from a coma, Xiao Ming finds himself locked in an abandoned minecart on Planet X. The minecart is parked on a straight, abandoned track. In front of him are two buttons, "F" "F" and
"B" "B".

Xiao Ming suddenly remembered that these two buttons could control the minecart to move forward and backward on the track. Press FF, it will advance 9797 meters. Press BB to go back 127127 meters.
Through the dim light, Xiao Ming saw that there was a surveillance probe 11 meters in front of him. He had to find a way to get the minecart parked just below the camera to get a chance to get help from his companions.
Perhaps, it can be done by manipulating FF and BB multiple times.

The power on the minecart is not enough, and the yellow warning light is blinking silently... Every time the FF or BB operation is performed, a certain amount of energy is consumed.
Xiao Ming quickly calculated how many operations it would take to accurately park the minecart 11 meters ahead.

What is the minimum number of operations required to achieve the goal.

The translation of this question is to ask
the solution of the smallest x+y of 97x-127y=1

Of course, this question can also be searched.

Brute-force search method

Here I will write a python code directly


x = 97
y = -127
ans = 100000#随便一个贼大的数
for i in range(300):
    for j in range(300):
        if i*x + j* y==1:
            ans = min(ans, i+j)
print(ans)

Bezu's solution (Euclidean)

This is the summation of the results obtained directly with our gadget

insert image description here

Modulo operation (congruence equation)

When it comes to modular arithmetic, he has two very magical functions.

1. Use modulo operation to retain the last few digits of the number
2. Use modulo operation to achieve no-carry addition

For
example, 6666666333 is reserved for the next three 3s. How to do it
directly 6666666333%1000 can be
added without carry, let alone
9+8 % 10 = 7

In addition, there is a law of nature
5 % 3 = 2
5% 2 == 3% 2 .

Of course, we also have the property of fast remainder,
fast exponentiation & fast exponentiation remainder

However, there is another property here.
For example, 5%3 %3 %3, you will find that
5%3 = 2
2% 3=2
. If you keep going on %, the effect may be the same, that is to say, if the first remainder ratio is taken modulo If the number is small, then there is no need to count it later.

Also about the modulo we write
a % b = m

Actually corresponds to
a = n*b + m

This means that we can also use this method to solve equations.
At this time, I am looking at the previous property
5%2 == 3%2

The equation can be written as
ax + my = b

x , y are integers. So I turned this thing into an equation. Then this equation is called a congruence equation.

So far, for solving the equation, if it is the solution of ax + by =1, we can use that Bezuel's theorem. Then for this congruence equation, we can also do this. They say it's a congruence equation.

Of course, the problem is how to convert such equations, equations with remainders, into linear equations. As long as you can switch, then you will be directly violent. Of course, you can be violent if you don't switch, just know a little more.

A date with frogs (example)

The two frogs met online, and they had a good time chatting, so they felt it was necessary to meet. They were delighted to find that they lived on the same line of latitude, so they agreed to hop westward until they met. But before they set off, they forgot one very important thing. They neither asked about the characteristics of each other nor agreed on a specific location to meet. However, the frogs are very optimistic. They feel that as long as they keep jumping in a certain direction, they will always meet each other. But unless the two frogs jumped to the same spot at the same time, they would never meet. To help the two optimistic frogs, you are asked to write a program to determine if and when the two frogs can meet.
We call these two frogs frog A and frog B respectively, and specify the origin at 0 degrees east longitude on the latitude line, the positive direction from east to west, and the unit length is 1 meter, so that we get a number line that is end-to-end. . Let the coordinate of the starting point of frog A be x, and the coordinate of the starting point of frog B is y. Frog A can jump m meters at a time, frog B can jump n meters at a time, and both frogs take the same amount of time to jump once. The total length of the latitude line is L meters. Now you need to ask them to jump a few times before they meet.
Input
consists of only one line of 5 integers x, y, m, n, L, where x≠y < 2000000000, 0 < m, n < 2000000000, 0 < L < 2100000000.
Output
output the number of jumps required to meet, if it is never possible to meet, output a line of "Impossible"
Sample Input
1 2 3 4 5
Sample Output
4

Here, we directly push the equation like this

(x + km)%L = (y+kn)%L
then we expand
x + km = L* y1 + remainder
y + kn = L*y2 + remainder

Merge
(mn)k + L(y1+y2) = yx

y1+y2 becomes an unknown t because they represent time
(mn)k + Lt = yx

That's the equation
ax + by = m
. Isn't that back to our original Bezuo solution?

But here is a detail, that is our handling of negative numbers. Here we focus on x, but the solution of x may be a negative number. Obviously, we want a positive number, so how to deal with this.
This direct set of templates
Our one is in the equation with the return value,
then the direct b / return value is assumed to be equal to c
, then directly
x = (x%c + c) %c
The following is the non-violent AC code . If
you change it yourself
insert image description here
, you may need to What do I do for y, all I can say is that math is a good thing.

find the inverse element

How do you say this, it's actually this thing

a % b = m

a % m = b % m = 1

Writing the equation is:
ax + by = 1

I read other people's code, in fact, it is similar to our code, but we have to pay attention to the case where x is a negative number.
For example,
13x == (1%5)
is
13x % 5 == 1% 5 Find the minimum value of our x (non-negative)

image.png

Summarize

Our focus today is this or that linear equation. As long as there is such a modulo operation in the equation, this linear equation, we can find a way to convert it

Guess you like

Origin blog.csdn.net/FUTEROX/article/details/123520423