Skip to content

Commit 83b6af4

Browse files
authored
Merge pull request inzva#72 from berkay-ozkan/master
Fix modular arithmetic property and fast exponention function
2 parents 02b75e4 + 07be73f commit 83b6af4

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

bundles/03-math-1/03_math1.pdf

16.3 KB
Binary file not shown.

bundles/03-math-1/latex/03_math1.tex

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ \subsubsection{Properties of Modular Arithmetic}
482482
\end{itemize}
483483
\paragraph{\textbf{Multiplication}}
484484
\begin{itemize}
485-
\item if $a = c$, then $a \mod{n} \cdot b \mod{n} \equiv c \mod{n}$.
485+
\item if $a \cdot b = c$, then $a \mod{n} \cdot b \mod{n} \equiv c \mod{n}$.
486486
\item if $a \equiv b \mod{n}$, then $a \cdot k \equiv b \cdot k \mod{n}$ for any integer $k$.
487487
\item if $a \equiv b \mod{n}$ and $c \equiv d \mod{n}$, then $(a \cdot c) \equiv (b \cdot d) \mod{n}$
488488
\end{itemize}
@@ -1348,16 +1348,24 @@ \subsection{Fast Exponentiation Approach }
13481348
#define mod 1000000007
13491349

13501350
long long fastExp(long long n, long long k){
1351-
if(k == 0) return 1;
1352-
if(k == 1) return n;
1351+
if (k == 0)
1352+
return 1;
13531353

1354-
long long temp = fastExp(n, k>>1);
1354+
n %= mod;
1355+
long long temp = fastExp(n, k >> 1);
13551356

13561357
// If k is odd return n * temp * temp
13571358
// If k is even return temp * temp
1358-
// Take mod, since we can have a large number that overflows from long long
1359-
if((k&1) == 1) return (n * temp * temp) % mod
1360-
return (temp * temp) % mod;
1359+
1360+
// The product of two factors that are each bounded by mod is bounded by
1361+
// mod squared. If we multiply this product with yet another factor that
1362+
// is bounded by mod, the result will be bounded by mod cubed. As mod is
1363+
// equal to 1000000007 by default, the result might not fit into
1364+
// long longs, leading to an overflow. To avoid that, we must take
1365+
// the modulus of n * temp before multiplying it with temp yet again.
1366+
if (k & 1)
1367+
return n * temp % mod * temp % mod;
1368+
return temp * temp % mod;
13611369
}
13621370
int main() {
13631371
long long n,k;
@@ -1366,14 +1374,13 @@ \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

13731381
return 0;
13741382
}
13751383

1376-
13771384
\end{minted}
13781385
\textbf{Output}
13791386

@@ -1668,4 +1675,4 @@ \subsection{Meet in the Middle }
16681675

16691676
\end{thebibliography}
16701677

1671-
\end{document}
1678+
\end{document}

0 commit comments

Comments
 (0)