最大公約数と最小公倍数を求める

C++Beginner
オンラインで実践に進む

はじめに

数学において、最大公約数(GCD: Greatest Common Divisor)と最小公倍数(LCM: Least Common Multiple)は便利な概念です。2 つの数の最大公約数は、それぞれの数の因数である最大の数であり、最大公約数は最大公約数とも呼ばれます。逆に、2 つ以上の整数の最小公倍数は、それらすべての倍数である最小の正の整数です。

プロジェクトディレクトリをセットアップする

まず、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";

    //変数宣言
    int n1, n2, i;

    //変数宣言と初期化
    int gcd = 1, lcm = 1;

    //コマンドライン(ユーザー)から入力を受け取る
    cout << "Enter two numbers to find their GCD and LCM (separated by a space): \n\n";
    cin >> n1 >> n2;

    //2 つの数の最大公約数と最小公倍数を計算する論理
    for ( i = 1; i <= n1 && i <= n2; i++)
    {
        //i は両方の数を完全に割り切る最小の値であり、したがって最大公約数
        if ((n1 % i == 0) && (n2 % i == 0))
        {
            gcd = i;
        }
    }

    lcm = (n1 * n2) / gcd;

    //2 つの数の最大公約数と最小公倍数をコマンドラインに表示する
    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";

    //変数宣言
    int n1, n2, i;

    //変数宣言と初期化
    int gcd = 1, lcm = 1;

    //コマンドライン(ユーザー)から入力を受け取る
    cout << "Enter two numbers to find their GCD and LCM (separated by a space): \n\n";
    cin >> n1 >> n2;

    //2 つの数の最大公約数と最小公倍数を計算する論理
    for ( i = 1; i <= n1 && i <= n2; i++)
    {
        //i は両方の数を完全に割り切る最小の値であり、したがって最大公約数
        if ((n1 % i == 0) && (n2 % i == 0))
        {
            gcd = i;
        }
    }

    lcm = (n1 * n2) / gcd;

    //2 つの数の最大公約数と最小公倍数をコマンドラインに表示する
    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;
}

まとめ

おめでとうございます。2 つの数の最大公約数(GCD)と最小公倍数(LCM)を計算するための C++ コードを学びました。これらのスキルを使えば、さまざまなアプリケーションに実装することができます。