简体   繁体   English

从一百万个整数整数中求模的最后一位; 需要解释吗?

[英]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: 假设我有一个随机的百万位数= x,这样:

len(str(x)) = 1000000

From looking at some explanations I can use x % (10 ** n) to find the last n digits. 通过查看一些解释,我可以使用x%(10 ** n)查找最后n个数字。 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的最后11位数字,我的代码将是:

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. 如果要查找数字的最后一位数字,可以将其除以10,除法的其余部分将是数字的最后一位数字。
  • 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. 如果要查找数字的最后两位数字,可以将其除以100,除法的其余部分将是数字的最后两位数字。
  • 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. 如果要查找数字的最后3位数字,可以将其除以1000,除法的其余部分将是数字的最后3位数字。
  • 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. 如果要查找数字的最后n位数字,可以将其除以10 ** n,除法的其余部分将是数字的最后n位数字。 In mathematical terms, the last n digits of number x are given by: 用数学术语来说,数字x的最后n数字由下式给出:

     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 . 因此7%3 = 1 I guess you know that ** is exponentiation, so 10**3 = 1000 . 我猜您知道**是幂运算,所以10**3 = 1000 Your example x % (10**11) divides x by 10**11 and tells you the remainder. 您的示例x % (10**11)x除以10**11并告诉您余数。 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. 一旦您拿走了10**11的最大可能倍数,换句话说就是最后n数字,那一定是剩下的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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