
Помогите! Нужно решить задачу на C++! Найти НОД И НОК числа. Даю кучу баллов!


Ответы на вопрос

Ответ:
Объяснение:
#include <iostream>
using namespace std;
long long NOD(long long a, long long b) {
while (a != 0 && b != 0) {
if (a > b) a = a % b;
else b = b % a;
}
return (a + b);
}
long long NOK(long long a, long long b) {
return a * b / NOD(a, b);
}
int main()
{
int a, b;
cin >> a >> b;
cout << NOD(a, b) << " " << NOK(a, b) << endl;
}



Finding the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) in C++
To find the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two numbers in C++, you can use the Euclidean algorithm. Here's how you can implement it:
```cpp
#include
// Function to calculate the GCD using the Euclidean algorithm int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); }
// Function to calculate the LCM using the GCD int lcm(int a, int b) { return (a * b) / gcd(a, b); }
int main() { int num1, num2; std::cout << "Enter two numbers: "; std::cin >> num1 >> num2;
int gcdResult = gcd(num1, num2); int lcmResult = lcm(num1, num2);
std::cout << "GCD: " << gcdResult << std::endl; std::cout << "LCM: " << lcmResult << std::endl;
return 0; } ```
In this code, we define two functions: `gcd()` and `lcm()`. The `gcd()` function calculates the GCD using the Euclidean algorithm, while the `lcm()` function calculates the LCM using the GCD. The `main()` function takes two numbers as input from the user, calls the `gcd()` and `lcm()` functions, and then prints the results.
To compile and run this code, you can use a C++ compiler such as g++:
``` $ g++ gcd_lcm.cpp -o gcd_lcm $ ./gcd_lcm Enter two numbers: 12 18 GCD: 6 LCM: 36 ```
In this example, the GCD of 12 and 18 is 6, and the LCM is 36.
Please let me know if you have any further questions or need additional assistance!


Похожие вопросы








Топ вопросов за вчера в категории Информатика
Последние заданные вопросы в категории Информатика
-
Математика
-
Литература
-
Алгебра
-
Русский язык
-
Геометрия
-
Английский язык
-
Химия
-
Физика
-
Биология
-
Другие предметы
-
История
-
Обществознание
-
Окружающий мир
-
География
-
Українська мова
-
Информатика
-
Українська література
-
Қазақ тiлi
-
Экономика
-
Музыка
-
Право
-
Беларуская мова
-
Французский язык
-
Немецкий язык
-
МХК
-
ОБЖ
-
Психология
-
Физкультура и спорт
-
Астрономия
-
Кыргыз тили
-
Оʻzbek tili