Site icon Learn C++

How To Compute The Greatest Common Divisor And Least Common Multiple in C++?

How To Compute The Greatest Common Divisor And Least Common Multiple in C++

The C++ 17 standard brings us a lot of useful methods, templates, numerics, and algorithms. Two of the great numeric functions are std::gcm and std::lcm which are defined in the <numeric> header that computes the greatest common divisor and least common multiple of two integers. In this post, we learn what std::gcm and std::lcm are, and how can we use them in modern C++.

What is std::gcm the greatest common divisor numeric function in C++?

In mathematics, the Greatest Common Divisor (GCD) also known as the Highest Common Factor (HCF) of two integer numbers is the largest number that exactly divides both numbers. In C++, the std::gcm greatest common divisor numeric function is defined in the <numeric> header that computes the greatest common divisor of the given two integers. 

Here is the syntax of std::gcm since C++17,

[crayon-6711f16ce62c1677254614/]

Here how we can find the greatest common divisor of two numbers in C++,

[crayon-6711f16ce62ca954860048/]

this will return 23 because both has 23 divisor which is the greatest one.

What is the std::lcm least common multiple numeric function in C++?

In mathematics, the Least Common Multiple (LCM) also known as the Lowest Common Multiple, or Smallest Common Multiple of two integer numbers is the lowest common multiple number of two integers In C++, the std::lcm least common multiple numeric function is defined in the <numeric> header that computes the lowest multiple number of the given two integers.

Here is the syntax of std::lcm since C++17,

[crayon-6711f16ce62cb252852904/]

Here how we can find the lowest common multiple, of two numbers in C++,

[crayon-6711f16ce62cd227458093/]

this will return 12 because 12 is the lowest common multiple of 12 and 6.

Is there a full example about std::gcm and std::lcm numeric functions in C++?

Here is a full example about std::gcm and std::lcm numeric functions in modern C++,

[crayon-6711f16ce62ce984323517/]

For more details about this feature in C++17 standard, please see these papers; P0295R0

C++ Builder is the easiest and fastest C and C++ compiler and IDE for building simple or professional applications on the Windows operating system. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for UIs.

There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.

Exit mobile version