print 10**1000 % 7
In C I get a syntax error because it exceeds the memory limit I guess. Can I somehow solve this easy in C or C++, such that it would give me a modulo of 10 to the power of 1000?
print 10**1000 % 7
In C I get a syntax error because it exceeds the memory limit I guess. Can I somehow solve this easy in C or C++, such that it would give me a modulo of 10 to the power of 1000?
In addition to that not being valid syntax in C/C++, it's bad practice in python.
If you do
pow(10,1000,7)
It will use modular exponentiation so it will be much faster than doing
10 ** 1000 % 7
you can use pow
for power operation. here the size of result is large value so you need to divide the problem into smaller part and solve smaller ones to get the solution in c or you'll need to handle large numbers.
you can apply modulus rules to reduce the problem as,
10^1000 % 7 =((10%7)^1000)%7
10^1000 % 7 =(((((10^10)%7)^10)%7)^10)%7
combine these rules and use to reduce the numbers generated in steps by (mod 10).use inbuilt pow()
function in c to get power of number as X^y=pow(x,y)
The most general way to solve these types of big-integer problems in small (e.g. 32-bit) registers is with exponentiation by squaring, and taking modulo at each step. E.g. 10^10 is still too big to fit in a 32-bit int, though you could probably just use a long these days.
In C (and C++ too AFAIK) this is not a valid syntax. You can use pow
function for exponentiation. But keep in mind that return value of pow
is double
and modulo operator works for int
. You need some cautions.
long result = (long)pow(10, 1000);
result = result % 7;
The easiest way to do this is to reduce the terms by the modulus. The general formula is
ab mod c ≡ (a mod c)(b mod φ(c)) mod c
So in this case you get
101000 mod 7 = (10 mod 7)(1000 mod φ(7)) mod 7.
10 mod 7 = 3
φ(7) = 6
1000 mod 6 = 4
34 = 81
81 mod 7 = 4
so 101000 mod 7 = 4
**
operator, you have to use the pow
function, that however works only for floating-point types; and the % operator works only for integral types, for FP types you have to use fmod
;1En
(say, 1E42
);fmod
on it, due to the finite precision of the mantissa. So, how does Python do? Under the hood, beyond the range of "normal" types it uses an arbitrary precision library. You can do the same in your C++ program, providing such library (for example you could use GMP).
But: the expression you provide can be calculated without actually computing 10**1000 and its modulus. Read Modulus power of big numbers