The principle and template of the remainder of a large number

It can be said that taking the remainder of a large number is a common problem. Today we will talk about it.

Code template:

for(int i=0;i<strlen(s);i++)
{
    
    
    ans=(ans*10+s[i]-'0')%n;//n代表我们对几取余
}
//最后的ans就是我们最终求模的结果。    

The principle of the remainder of a large number: Starting from the first digit of the string, take the remainder, store the remainder and add it to the next digit, and continue to take the remainder.

In fact, it is to simulate the process of our hand counting time:

The so-called remainder is not the process of dividing to get the remainder. The algorithm of this program is actually the same as our manual division process. Think about how we do the calculations?
For example, the
highest digit of 4147 /3 starts, 4/3=1, and 1 is left, and then borrowed to the lower digit, the next digit is 1, and the borrow of the higher digit is 1×10+1= 11,
11/3=3, 2 remaining, continue to lend to the next bit=4+2×10=24, 24/3=8, just cut off, the last bit will not be borrowed, which
is 7/ 3=2, 1 is left, and the final remainder is the remainder of 4147 /3.
The process of calculating the remainder of large numbers in your program is not just simulating the process of dividing by pen!

Retrieved from: https://zhidao.baidu.com/question/687640069321980404.html

Look at an example
Insert picture description here
question : The number given in the question has exceeded 2 and 18 has already exploded long long.
This is obviously a question of taking the remainder of a large number. According to the title, we take the remainder of 9.
Insert picture description here
The remainder is 7, and the corresponding English letter is G. So the result is G.

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/115325491