GCDMOD - Editorial

Problem Link

Practice

Contest

Author: Bhuvnesh Jain

Tester: Mark Mikhno

Editorialist: Bhuvnesh Jain

Difficulty

EASY-MEDIUM

Prerequisites

GCD, Modular Exponentiation, Overflow-handling

Problem

Find the GCD of A^N + B^N and (A - B) modulo 1000000007.

Explanation

The only property required to solve the complete problem is GCD(U, V) = GCD(U % V, V). If you are unfamiliar with this, you can see the proof here.

Now the problem remains finding the value of (A^N + B^N) % (A - B). This is can be easily done using modular exponentiation in O(\log{N}) complexity. You can read about on wikipedia and implementation at Geeks for Geeks.

With the above 2 things, you are almost close to the full solution. The only thing left now is to handle overflows in languages like C++ and Java. First, understand why we might get overflow and then how we handle it.

Note that we are computing A^N % (A - B). Since, (A - B) can be of the order {10}^{12}, the intermediate multiplications during exponentiation can be of the order of {10}^{12} * {10}^{12} = {10}^{24} which is too large to fit in long long data type. Due, to overflows, you will get the wrong answer. To deal with overflows, below are 3 different methods:

  • Using “int_128” inbuilt datatype in C++. For details, you can refer to [mgch solution].

This approach has a complexity of O(1).

  • Using an idea similar to modular exponentiation. Instead of carrying out multiplication operations, we use addition operations. Below is a pseudo-code for it:

	# Returns (a * b) % m
	def mul_mod(a, b, m):
		x = 0, y = a
		while b > 0:
			if b & 1:
				# No overflows in additons.
				x = (x + y) % m
			y = (y + y) % m
			b >>= 1
		return x

This approach has a complexity of O(\log{B}).

  • Using idea similar to karatsuba trick. This is specific only to this question as constraints are upto {10}^{12} and not {10}^{18}. We can split a as a_1 * {10}^{6} + a_2 and b as b_1 * {10}^{6} + b_2. Note that all a_1, b_1, a_2, b_2 are now less than or equal to {10}^{6}. Now we multiply both of them and there will be no overflow now in intermediate multiplications as the maxmium value can be {10}^{12} * max(a_1, b_1) = {10}^{18}. The setter code using this approach.

The time complexity of this approach is O(1).

The final corner case to solve the problem is the case when A = B. This is because calculating A^N + B^N % (A - B), would lead to runtime error while calculating modulo 0. For this case, we use the fact that GCD(U, 0) = U. Thus the answer is simply A^N + B^N.

The last part is just printing the answer modulo 1000000007.

The overall time complexity is O(\log{N} + \log{max(A, B)}). The first is for calculating the modular exponentiation and the second part is for calculating GCD. The space complexity is O(1).

Once, you are clear with the above idea, you can see the author implementation below for help.

Note that since the number of test cases was small, another approach which iterates over divisors of (A - B) to find the answer will also pass within the time limit if proper care is taken of overflows and the case A = B.

Feel free to share your approach as well, if it was somewhat different.

Time Complexity

O(\log{N} + \log{max(A, B)})

Space Complexity

O(1)

SOLUTIONS:

Author’s solution can be found here.

Tester’s solution can be found here.

Editorialist’s solution can be found here.

My approach-

First of all the gcd will be less than or equal to a-b (that’s obvious)

an - bn is always divisible by a-b and gcd(a,b)=gcd(b,r) where a=bq+r

by this property now we have to calculate gcd(2*bn,a-b)

Now let us assume that a-b has some number of prime factors p(repeatition considered)

we take its gcd with b…let it be g…now all the prime factors of a-b which are also present in b are now in g…so we divide a-b by g…let a-b/g=c

Now we again take gcd of c with b and divide c with it…The idea here is we are finding all the prime factors of a-b which are also present in b by taking gcd without any powers of b as it may result in overflow

After each step we keep on multiplying the answer with the gcd found.The process will terminate if we have introduced b n times or gcd of c and b has become 1

It works because for any k<n if gcd(bk,c)=1 then gcd(bk+1,c)=1

I think i have complicated the explanation a bit.
Here is my code for better understanding-> https://www.codechef.com/viewsolution/19638654

My approach was to find gcd(a-b,2b^n,2a^n)

Here we go

if(a!=b)
{
g=gcd(a,b)

p=1

inside for loop i =1 to n

{ p=p * g;

if( ( ans=gcd(2 * p,a-b) )==gcd(2 * p * g,a-b) )

break;

} ans%=mod;

}
else ans=2(b^n)* use modular expo

Python is always there to save in these situations :slight_smile:

1 Like

True that. This question reduces to a direct Fast-Exponentiation (implementation wise) if you use python.

result = ((pow(A, N, mod) mod + (pow(B, N, mod) mod)) % mod)

if A == B:

   print((fractions.gcd(result, abs(A-B))) % mod)

else:
    if N == 1:
        print(fractions.gcd((pow(A,1)+pow(B, 1)), abs(A-B)) % mod)

    else:
        print(fractions.gcd((pow(A, 2)+pow(B, 2)), abs(A-B)) % mod)
I think this is most easiest solution

Tried solving using both exponentiation and iterating over divisors of (A-B) , but did not take care of overflows in C++ !

Have a look at my "N independent " solution(except when a=b), of course it is wrong but it still passes . Test cases where it should have failed…
some test cases :

  1. A=10, B=2, N=1 my answer=8(correct is 4)
  2. A=12, B=3,N=1 my answer=9(correct is 3)
  3. A=18,B=2,N>2
  4. A=22,B=6,N>2
  5. A=26,B=10,N>2
    there are many many more test cases where it should have failed.
    Test cases were very weak. I understand that making good test cases is difficult task but this time they are extremely weak.

my solution

My code absolutely worked well in other compilers but codechief refused to take my code . The results were wrong answer but why ? Here is my code and result …alt text
alt text

I used the property: gcd(a,b)=gcd(b,r) where a=bq+r.

If we do the binomial expansion of ((a-b)+b)^n + b^n , we will find all terms having a-b as factors except 2b^n . GCD will now contain the primes present in a-b and 2b^n and the respective primes will have the exponent minimum of the exponent found in a-b and 2*b^n.