C++의 std::gcd 함수

Jinku Hu 2023년10월12일
  1. std::gcd 함수를 사용하여 C++에서 두 정수의 최대 공약수 계산
  2. std::lcm 함수를 사용하여 C++에서 두 정수의 최소 공배수 계산
  3. std::midpoint 함수를 사용하여 C++에서 두 숫자의 중간점 계산
C++의 std::gcd 함수

이 기사에서는 C++의 STL 수치 라이브러리에서 std::gcd 및 기타 유용한 수학 함수를 활용하는 방법을 설명합니다.

std::gcd 함수를 사용하여 C++에서 두 정수의 최대 공약수 계산

STL은 <algorithm> 헤더를 사용하여 여러 알고리즘을 제공하지만 강력한 수학 기능도 제공하며 그 중 일부는 숫자 알고리즘으로 간주될 수 있습니다. 이러한 기능은 numeric 헤더를 사용하여 제공됩니다.

두 정수의 최대 공약수를 계산하는 std::gcd 함수를 살펴보겠습니다. 최대 공약수는 주어진 각 정수를 나누는 가장 큰 양의 정수입니다.

std::gcd는 두 개의 정수 값(mn)을 취하고 |m||n|의 최대 공약수를 반환합니다. ’m’과 ’n’이 모두 0이면 함수도 0을 반환합니다. 다음 예제 코드는 std::gcd의 기본 사용법을 보여주고 해당 결과를 콘솔에 출력합니다.

#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

using std::cout;
using std::endl;
using std::setw;
using std::vector;

int main() {
  std::vector<std::pair<int, int>> vec = {
      {12125, 1235}, {124, 1122}, {-1235, 321}, {12, 144}};

  for (const auto &item : vec) {
    cout << "Greatest common divisor of " << setw(5) << item.first << " and "
         << setw(5) << item.second << " is "
         << std::gcd(item.first, item.second) << endl;
  }

  return EXIT_SUCCESS;
}

출력:

Greatest common divisor of 12125 and  1235 is 5
Greatest common divisor of   124 and  1122 is 2
Greatest common divisor of -1235 and   321 is 1
Greatest common divisor of    12 and   144 is 1

std::lcm 함수를 사용하여 C++에서 두 정수의 최소 공배수 계산

수치 라이브러리에서 제공되는 또 다른 유사한 함수는 두 정수의 최소 공배수를 계산하는 std::lcm입니다. 이 함수는 std:gcd와 유사한 두 개의 정수를 수용하고 |m||n|(인수 표시)의 최소공배수를 반환합니다.

이 두 함수에는 모두 constexpr 지정자가 있습니다. 이는 상수 표현식에 사용될 수 있으며 함수도 인라인 분류를 얻을 수 있음을 의미합니다.

#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

using std::cout;
using std::endl;
using std::setw;
using std::vector;

int main() {
  std::vector<std::pair<int, int>> vec = {
      {12125, 1235}, {124, 1122}, {-1235, 321}, {12, 144}};

  for (const auto &item : vec) {
    cout << "Least common multiple of " << setw(5) << item.first << " and "
         << setw(5) << item.second << " is "
         << std::lcm(item.first, item.second) << endl;
  }

  return EXIT_SUCCESS;
}

출력:

Least common multiple of 12125 and  1235 is 2994875
Least common multiple of   124 and  1122 is 69564
Least common multiple of -1235 and   321 is 396435
Least common multiple of    12 and   144 is 144

std::midpoint 함수를 사용하여 C++에서 두 숫자의 중간점 계산

std::midpoint는 사용자가 오버플로에 대해 걱정하지 않고 주어진 두 숫자의 절반을 계산할 수 있는 기능입니다. 즉, 합이 64비트 정수의 상한보다 큰 두 개의 큰 정수의 절반을 계산하려고 하면 오버플로가 발생하고 결과가 올바르지 않습니다.

예를 들어 다음 코드 조각은 두 정수의 중간점을 찾으려고 합니다. 여기서 하나는 uint64_t에 저장할 수 있는 최대 수와 같고 다른 하나는 10배 작습니다. 일반적인 산술 연산자를 사용한 계산은 잘못된 숫자를 산출하는 반면 std::midpoint는 올바른 결과를 반환합니다.

이 기능은 C++20 표준 이후로 언어의 일부였으며 이전 버전에서는 사용하지 못할 수도 있습니다. std::midpoint는 포인터 값에서도 작동하지만 주어진 포인터는 동일한 배열의 요소여야 합니다. 그렇지 않으면 동작이 정의되지 않습니다.

#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

using std::cout;
using std::endl;
using std::setw;
using std::vector;

int main() {
  uint64_t a = std::numeric_limits<uint64_t>::max();
  uint64_t b = std::numeric_limits<uint64_t>::max() - 10;

  cout << "a: " << a << '\n'
       << "b: " << b << '\n'
       << "Incorrect: " << setw(20) << (a + b) / 2 << '\n'
       << "Correct  : " << setw(20) << std::midpoint(a, b) << endl;

  return EXIT_SUCCESS;
}

출력:

a: 18446744073709551615
b: 18446744073709551605
Incorrect:  9223372036854775802
Correct  : 18446744073709551610
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook