Time and Numeric Utilities
GCD LCM
Greatest common divisor and least common multiple help compare repeating numeric sizes.
gcd
`std::gcd` finds the largest integer that divides two values evenly.
lcm
`std::lcm` finds the smallest positive integer that is a multiple of both values.
GCD LCM
gcd_lcm.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <numeric>
int main() {
int width = 12;
int height = 8;
int common = std::gcd(width, height);
int repeat = std::lcm(width, height);
std::cout << "width=" << width << std::endl;
std::cout << "gcd=" << common << std::endl;
std::cout << "lcm=" << repeat << std::endl;
return 0;
}
#include <iostream>
#include <numeric>
int main() {
int width = 7;
int height = 8;
int common = std::gcd(width, height);
int repeat = std::lcm(width, height);
std::cout << "width=" << width << std::endl;
std::cout << "gcd=" << common << std::endl;
std::cout << "lcm=" << repeat << std::endl;
return 0;
}
#include <iostream>
#include <numeric>
int main() {
int width = 18;
int height = 8;
int common = std::gcd(width, height);
int repeat = std::lcm(width, height);
std::cout << "width=" << width << std::endl;
std::cout << "gcd=" << common << std::endl;
std::cout << "lcm=" << repeat << std::endl;
return 0;
}
width ← 12, height ← 8, common ← 4, repeat ← 24
4int main() {5 int width→ 12 = 12; //@width=18, 767 int height→ 8 = 8;8 int common→ 4 = std::gcd(width12, height8);9 int repeat→ 24 = std::lcm(width12, height8);1011 std::cout << "width=" << width12 << std::endl;12 std::cout << "gcd=" << common4 << std::endl;13 std::cout << "lcm=" << repeat24 << std::endl;14 return 0;15}outputwidth=12 gcd=4 lcm=24
width ← 7, height ← 8, common ← 1, repeat ← 56
4int main() {5 int width→ 7 = 7;67 int height→ 8 = 8;8 int common→ 1 = std::gcd(width7, height8);9 int repeat→ 56 = std::lcm(width7, height8);1011 std::cout << "width=" << width7 << std::endl;12 std::cout << "gcd=" << common1 << std::endl;13 std::cout << "lcm=" << repeat56 << std::endl;14 return 0;15}outputwidth=7 gcd=1 lcm=56
width ← 18, height ← 8, common ← 2, repeat ← 72
4int main() {5 int width→ 18 = 18;67 int height→ 8 = 8;8 int common→ 2 = std::gcd(width18, height8);9 int repeat→ 72 = std::lcm(width18, height8);1011 std::cout << "width=" << width18 << std::endl;12 std::cout << "gcd=" << common2 << std::endl;13 std::cout << "lcm=" << repeat72 << std::endl;14 return 0;15}outputwidth=18 gcd=2 lcm=72