Understand algorithms in seconds | Example analysis of number theory algorithms: Alibaba’s treasure and Euler function examples

Mathematics (math) is widely used in computer science and is an auxiliary subject of programming. Some people have said: "All computer problems ultimately boil down to mathematical problems!" Number theory is a very large branch of mathematics. For programs Design is important, but it is not all of programming. This chapter will discuss several types of number theory problems and implement them with programs.

01, Case Study: Alibaba’s Treasure

Problem Description:

Alibaba and Margina came to a street full of gold. They wanted to take a few pieces of gold back, but the city management here was worried that they would take too much, so they asked Alibaba and Margina to play a game to determine the final amount of gold.

The rules of the game are as follows:

Assume that the length of the road is n meters (the left endpoint is 0 and the right endpoint is n), and a number k is given (the usage of k will be mentioned below).

Let Alibaba’s initial gold quantity be A, and Margina’s initial gold quantity be B. Alibaba starts from 1 and goes to n-1, and Margina starts from n-1 and goes to 1. The speed of both of them is 1m/s.

Assume that at a certain moment (must be an integer) Alibaba's position is x and Margina's position is y. If gcd(n,x)=1 and gcd(n,y)=1, then Alibaba's gold amount A will become A*kxkg, and Margina's gold amount B will become B*kykg. The game ends when Alibaba reaches n-1.

Alibaba wants to know the value of A+B at the end of the game.

The answer is modulo 109+7.

Enter description:

A row of four integers n,k,A,B.

Output description:

Output an integer representing the answer.

Example:

Guess you like

Origin blog.csdn.net/qq_41640218/article/details/133744793