C++ std::gcd
The greatest common divisor is the longest whole-unit piece that divides both ribbon lengths evenly.
A simple example
std::gcd
- Start with 6 and 4
- Do this Find the largest shared divisor
- Result 2
#include <iostream>
#include <numeric>
int main() {
std::cout << (std::gcd(6, 4)) << '\n';
}
2
Syntax
std::gcd(24, 36)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonPack two ribbon lengths into equal pieces
A craft shop has two lengths of ribbon and wants equal pieces without leftovers. Find the largest length that divides both rolls before cutting the first strip.
#include <numeric>
#include <iostream>
int main() {
std::cout << (std::gcd(24, 36)) << "\n";
return 0;
}
12
A 24-centimetre ribbon yields two pieces of length twelve. A 36-centimetre ribbon yields three.
Cut equal fabric squares
A textile student has a rectangular piece measuring 18 by 30 centimetres. She wants the largest square size that tiles it without offcuts.
Using 18 · 30 gives 6 for this measurement.
Make identical sample kits
A teacher has 42 red counters and 28 blue counters. He wants the largest number of identical kits that uses every counter.
Using 42 · 28 gives 14 for this measurement.
What to watch for
Use the same smallest whole unit for both measurements before computing a divisor.