Advertisement
Solingen

z10.1.cpp

Dec 22nd, 2024
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Вычисление НОД двух чисел
  5. long long gcd(long long a, long long b)
  6. {
  7.     while (b != 0)
  8.     {
  9.         long long t = a % b;
  10.         a = b;
  11.         b = t;
  12.     }
  13.     return a;
  14. }
  15.  
  16. // Вычисление НОК двух чисел
  17. long long lcm(long long a, long long b)
  18. {
  19.     return (a / gcd(a, b)) * b;
  20.     // важно (a/gcd(a,b))*b, чтобы избежать переполнения
  21. }
  22.  
  23. int main()
  24. {
  25.     int k;
  26.     cout << "Сколько чисел: ";
  27.     cin >> k;
  28.  
  29.     if (k <= 0)
  30.     {
  31.         cout << "Неверное k\n";
  32.         return 0;
  33.     }
  34.  
  35.     long long x;
  36.     cin >> x; // первое число
  37.     long long currentGCD = x;
  38.     long long currentLCM = x;
  39.     for (int i = 1; i < k; i++)
  40.     {
  41.         cin >> x;
  42.         currentGCD = gcd(currentGCD, x);
  43.         currentLCM = lcm(currentLCM, x);
  44.     }
  45.  
  46.     cout << "НОД = " << currentGCD << endl;
  47.     cout << "НОК = " << currentLCM << endl;
  48.  
  49.     return 0;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement