Найти НОД и НОК

C++Beginner

Введение

В математике наибольший общий делитель (НОД) и наименьшее общее кратное (НОК) - полезные понятия. Наибольший общий делитель двух чисел, также называемый наибольшим общим делителем, - это наибольшее число, являющееся делителем обоих чисел. Наоборот, наименьшее общее кратное двух или более целых чисел - это наименьшее положительное целое число, которое кратно всем из них.

Настройте директорию проекта

Сначала создайте новую папку с помощью команды mkdir, а затем настройте проект на C++ в этой директории с помощью команды cd. Например:

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;
}

Резюме

Поздравляем, вы узнали код на C++, который вычисляет НОД и НОК двух чисел. С этими знаниями вы можете реализовать их в различных приложениях.