@@ -1348,6 +1348,7 @@ \subsection{Fast Exponentiation Approach }
13481348#define mod 1000000007
13491349
13501350long long fastExp(long long n, long long k){
1351+ n % = mod;
13511352 if(k == 0) return 1;
13521353 if(k == 1) return n;
13531354
@@ -1356,6 +1357,13 @@ \subsection{Fast Exponentiation Approach }
13561357 // If k is odd return n * temp * temp
13571358 // If k is even return temp * temp
13581359 // Take mod, since we can have a large number that overflows from long long
1360+
1361+ // The product of two factors that are each bounded by mod is bounded by
1362+ // mod squared. If we multiply this product with yet another factor that
1363+ // is bounded by mod, the result will be bounded by mod cubed. As mod is
1364+ // equal to 1000000007 by default, the result might not fit into
1365+ // long longs, leading to an overflow. To avoid that, we must take
1366+ // the modulus of n * temp before multiplying it with temp yet again.
13591367 if((k&1) == 1) return ((n * temp) % mod * temp) % mod;
13601368 return (temp * temp) % mod;
13611369}
@@ -1366,7 +1374,7 @@ \subsection{Fast Exponentiation Approach }
13661374 // Calculate the runtime of the function.
13671375 clock_t tStart = clock();
13681376
1369- long long res = expon (n, k);
1377+ long long res = fastExp (n, k);
13701378 printf("Time taken: % .6fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
13711379 printf("% lld\n", res);
13721380
@@ -1668,4 +1676,4 @@ \subsection{Meet in the Middle }
16681676
16691677\end {thebibliography }
16701678
1671- \end {document }
1679+ \end {document }
0 commit comments