C++ and Mathematics
Number theory in code
The Euclidean algorithm, GCD and LCM, primes, divisors, digits and modular arithmetic.
60 min 8 questions
01The Euclidean algorithm
Key fact: and . The numbers shrink quickly, so the algorithm takes steps; the "slowest" case is two consecutive Fibonacci numbers. LCM: (divide first to avoid overflow).
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}02Primes and divisors
is prime if it has no divisor from to : if with , then . In code we write the condition as i * i <= n to avoid floating-point roots.
For a whole range the Sieve of Eratosthenes is faster: for each prime , cross out its multiples.
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}03Modular arithmetic
, so the remainder of a huge power can be computed by reducing at every step, so the numbers never grow. For example, can be computed by a loop that only ever stores 0–6.
Key formulas
Euclidean algorithm
LCM
Why checking up to suffices
Remainder of a product
Worked examples
Example 1
Trace gcd(48, 18).
(48, 18) -> (18, 12) -> (12, 6) -> (6, 0) => 6What does this code print?
#include <iostream>
using namespace std;
int gcd(int a, int b) {
while (b != 0) { int t = a % b; a = b; b = t; }
return a;
}
int main() {
cout << gcd(84, 120);
}Sample content: questions and lessons are illustrative and are not taken from official exams.
