简体   繁体   中英

Finding last digits with modulo from a million digits int; need an explanation?

Lets say I have a random million digit number = x, such that:

len(str(x)) = 1000000

From looking at some explanations I can use x % (10 ** n) to find the last n digits. But I can't wrap my head around why that works.

Such that if I wanted to find the last 11 digits of x my code would be:

x % (10 ** 11)

Could someone shed some light on this for me?

Think of it this way:

  • If you want to find the last digit of a number, you can divide it by 10, and the remainder of the division will be the last digit of the number.
  • If you want to find the last 2 digits of a number, you can divide it by 100, and the remainder of the division will be the last 2 digits of the number.
  • If you want to find the last 3 digits of a number, you can divide it by 1000, and the remainder of the division will be the last 3 digits of the number.
  • If you want to find the last n digits of a number, you can divide it by 10**n, and the remainder of the division will be the last n digits of the number. In mathematical terms, the last n digits of number x are given by:

     x % (10 ** n) 

In case you don't know, the modulo operator (%) divides two numbers and returns the remainder .

% returns the remainder after division, just like in primary school when you learned long division. So 7%3 = 1 . I guess you know that ** is exponentiation, so 10**3 = 1000 . Your example x % (10**11) divides x by 10**11 and tells you the remainder. That must be the digits left over once you take away the largest possible multiple of 10**11 , in other words the last n digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM