Reputation: 2724
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?
Upvotes: 1
Views: 2415
Reputation: 16279
Think of it this way:
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.
Upvotes: 6
Reputation: 1182
%
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.
Upvotes: 2