0

How to do this type of problems efficiently in less time? I have tried to do this problem in Python but it's taking so much time. I have been thinking that maybe ^ mean xor not power but according to them it was power. This is a problem from a coding competition.

Petr
  • 9,812
  • 1
  • 28
  • 52
graypacket
  • 98
  • 1
  • 11

3 Answers3

4

In general case, yes, you should better use modular exponentiation, and this is indeed rather simple, as @F.Ju shown. However, with a bit of math you can calculate the sum completely with pen and paper1.

The key thing to note is the fact the the exponent (2453467) is very close to the modulus (2453468), and this calls for a much simpler representation of x^2453467 mod 2453468. Indeed, if 2453468 were prime, then x^2453467 mod 2453468 would be always 1 according to the Fermat's little theorem.

It is not prime though, but it has a very simple representation of 2*2*613367. So we can remember the Euler's theorem, and find that phi(2453468) equals to 1226732, and so 2453467=2*phi(2453468)+3. Thus for every x that is relatively prime with 2453468 we have x^1226732=1, and, as 2453467 is 1226732*2+3, we have x^2453467 mod 2453468=x^3 mod 2453468.

Let us then consider the numbers that are not relatively prime to 2453468. In out range (1 to 999999) there are three kinds of numbers that are not relatively prime to 2453468. One is 613367, and it is relatively easy to proof that 613367^(2k+1) mod 2453468=613367 for each k.

The other kind are numbers divisible by 4. For a number x=4k we need to find (4k)^2453467 mod (4*613367). It is equivalent to 4*(4^2453466*k^2453467 mod 613367) mod (4*613367) and by little Fermat's theorem this reduces to (4k)^3 mod (4*613367).

The final kind is the numbers divisible by 2, but not 4, and they can be treated the same was as the previous kind.

As a result, we have that

For every x from 1 to 999999,

x^2453467 mod 2453468 = x^3 mod 2453468

Hence, we need to calculate

sum(x^3) mod 2453468

for x from 1 to 999999.

But the sum under the modulus operation is, as is well known, just (n(n+1)/2)^2, with n being 999999. Therefore, our answer is 499999500000^2 mod 2453468, which evaluates to 2385752.

1 Well, almost. I used Python to do simple arithmetic.

Petr
  • 9,812
  • 1
  • 28
  • 52
2

In python code

answer = 0
for i in range (1, 1000000):
    answer += pow(i, 2453467, 2453468)
print answer % 2453468

The speed seems fast enough

throwit
  • 714
  • 3
  • 13
  • You actually need to print `answer%2453468`, or better have `answer = (answer + pow(...)) % 2453468` inside the loop. – Petr Oct 21 '15 at 07:54
1

https://en.wikipedia.org/wiki/Modular_exponentiation

Focus on the Memory efficient method of calculation. Should be pretty straightforward to implement.

drewcd
  • 11
  • 1