std::lcm(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… std::lcm(3) β€” C++ Standard Libary, bestie edition πŸ’…

okay so this is the std::lcm(3) page, lowkey iconic, and we're about to make least common multiples make sense. No cap. πŸ¦‹


πŸŽ€ NAME πŸŽ€

std::lcm - std::lcm β€” that's literally the whole name line, bestie. It's giving "the function is called std::lcm and the manual entry is also std::lcm". Periodt. ✨


✨ Synopsis ✨

Defined in header <numeric> β€” and here's the signature, copied exactly because we do not play with code:

Defined in header <numeric>
template< class M, class N >                         (since C++17)
constexpr std::common_type_t<M, N> lcm( M m, N n );

It computes the least common multiple of the integers m and n. That's the main character energy of this function. πŸ’–

🚨 Type vibe check: if either M or N is not an integer type, or if either is (possibly cv-qualified) bool, the program is ill-formed. No cap, that's not a suggestion.
πŸ’€ Undefined behavior alert: the behavior is undefined if |m|, |n|, or the least common multiple of |m| and |n| is not representable as a value of type std::common_type_t<M, N>. Like, do not test this at home, fr fr.

πŸ¦‹ Parameters πŸ¦‹

  • m, n β€” integer values.

🌸 Return value 🌸

If either m or n is zero, returns zero. Otherwise, returns the least common multiple of |m| and |n|.


πŸŽ€ Exceptions πŸŽ€

Throws no exceptions. It's giving calm, unbothered, moisturized. ✨


πŸ’œ Notes πŸ’œ

Feature-test macro vibe check:

  • __cpp_lib_gcd_lcm β€” value 201606L; std (C++17); feature std::gcd, std::lcm.

πŸ”₯ Example πŸ”₯

Run this code, bestie:

// Run this code

#include <iostream>
#include <numeric>

#define OUT(...) std::cout << #__VA_ARGS__ << " = " << __VA_ARGS__ << '\n'

constexpr auto lcm(auto x, auto... xs)
{
    return ((x = std::lcm(x, xs)), ...);
}

int main()
{
    constexpr int p{2 * 2 * 3};
    constexpr int q{2 * 3 * 3};
    static_assert(2 * 2 * 3 * 3 == std::lcm(p, q));
    static_assert(225 == std::lcm(45, 75));

    static_assert(std::lcm( 6,  10) == 30);
    static_assert(std::lcm( 6, -10) == 30);
    static_assert(std::lcm(-6, -10) == 30);

    static_assert(std::lcm( 24, 0) == 0);
    static_assert(std::lcm(-24, 0) == 0);

    OUT(lcm(2 * 3, 3 * 4, 4 * 5));
    OUT(lcm(2 * 3 * 4, 3 * 4 * 5, 4 * 5 * 6));
    OUT(lcm(2 * 3 * 4, 3 * 4 * 5, 4 * 5 * 6, 5 * 6 * 7));
}

🌈 Output 🌈

lcm(2 * 3, 3 * 4, 4 * 5) = 60
lcm(2 * 3 * 4, 3 * 4 * 5, 4 * 5 * 6) = 120
lcm(2 * 3 * 4, 3 * 4 * 5, 4 * 5 * 6, 5 * 6 * 7) = 840

⭐ See also ⭐

  • gcd β€” computes the greatest common divisor of two integers; (C++17) (function template).

made with πŸ’– by your Unix bestie Β· source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::lcm(3) Β· that's the footer, periodt 🫢

πŸ“¦ where this page comes from