최대공약수 (GCD) 와 최소공배수 (LCM) 구하기

C++Beginner
지금 연습하기

소개

수학에서 GCD (최대공약수, Greatest Common Divisor) 와 LCM (최소공배수, Least Common Multiple) 은 유용한 개념입니다. 최대공약수는 두 수의 공통 약수 중 가장 큰 수입니다. 반대로, 두 개 이상의 정수의 최소공배수는 모든 수의 배수 중 가장 작은 양의 정수입니다.

프로젝트 디렉토리 설정

먼저, mkdir 명령어를 사용하여 새 폴더를 생성하고, cd 명령어를 사용하여 해당 디렉토리에 C++ 프로젝트를 설정합니다. 예를 들어 다음과 같습니다.

mkdir ~/project
cd ~/project

새 C++ 파일 생성

선호하는 텍스트 편집기를 사용하여 main.cpp라는 새 파일을 생성합니다. 예를 들어 다음과 같습니다.

touch main.cpp

C++ 코드 작성

다음 C++ 코드를 복사하여 main.cpp 파일에 붙여넣습니다.

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the GCD and LCM calculator!\n\n\n";
    cout << "===== Program to find the GCD and LCM of two numbers =====\n\n";

    //variable declaration
    int n1, n2, i;

    //variable declaration and initialization
    int gcd = 1, lcm = 1;

    //taking input from the command line (user)
    cout << "Enter two numbers to find their GCD and LCM (separated by a space): \n\n";
    cin >> n1 >> n2;

    //logic to calculate the GCD and LCM of the two numbers
    for ( i = 1; i <= n1 && i <= n2; i++)
    {
        //i is the least value that perfectly divides both the numbers and hence the GCD
        if ((n1 % i == 0) && (n2 % i == 0))
        {
            gcd = i;
        }
    }

    lcm = (n1 * n2) / gcd;

    //print the GCD and LCM of the two numbers on the command line
    cout << "\nThe GCD of the two numbers " << n1 << " and " << n2 << " is : " << gcd << endl;
    cout << "\nThe LCM of the two numbers " << n1 << " and " << n2 << " is : " << lcm << endl;
    cout << "\nThanks for using GCD and LCM calculator!\n\n\n";

    return 0;
}

코드 컴파일 및 실행

코드를 컴파일하고 실행하려면 터미널에서 다음 명령을 사용하십시오.

g++ main.cpp -o main && ./main

최종 코드

전체 코드를 다시 한 곳에 모았습니다.

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the GCD and LCM calculator!\n\n\n";
    cout << "===== Program to find the GCD and LCM of two numbers =====\n\n";

    //variable declaration
    int n1, n2, i;

    //variable declaration and initialization
    int gcd = 1, lcm = 1;

    //taking input from the command line (user)
    cout << "Enter two numbers to find their GCD and LCM (separated by a space): \n\n";
    cin >> n1 >> n2;

    //logic to calculate the GCD and LCM of the two numbers
    for ( i = 1; i <= n1 && i <= n2; i++)
    {
        //i is the least value that perfectly divides both the numbers and hence the GCD
        if ((n1 % i == 0) && (n2 % i == 0))
        {
            gcd = i;
        }
    }

    lcm = (n1 * n2) / gcd;

    //print the GCD and LCM of the two numbers on the command line
    cout << "\nThe GCD of the two numbers " << n1 << " and " << n2 << " is : " << gcd << endl;
    cout << "\nThe LCM of the two numbers " << n1 << " and " << n2 << " is : " << lcm << endl;
    cout << "\nThanks for using the GCD and LCM calculator!\n\n\n";

    return 0;
}

요약

축하합니다! 두 숫자의 최대공약수 (GCD) 와 최소공배수 (LCM) 를 계산하는 C++ 코드를 배웠습니다. 이 기술을 통해 다양한 애플리케이션에 적용할 수 있습니다.