Advertisement
RobertDeMilo

НОД (GreatestCommonDivisor)

Sep 9th, 2023 (edited)
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. Для нахождения наибольшего общего делителя в C++ есть удобная функция gcd из заголовочного файла <numeric>.
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.     int a, b;
  9.     cin >> a >> b;
  10.     // Числа a и b должны быть натуральными
  11.     while (b != 0) {
  12.         int c = b;
  13.         b = a % b;
  14.         a = c;
  15.     }
  16.     cout << a << endl;
  17. }
  18. *******************************************************************************************************************
  19. #include <iostream>
  20.  
  21. using namespace std;
  22.  
  23. int GreatestCommonDivisor(int a, int b)
  24. {
  25.     while (a > 0 && b > 0)
  26.     {
  27.         if (a > b)
  28.         {
  29.             a %= b;
  30.         }
  31.         else
  32.         {
  33.             b %= a;
  34.         }
  35.     }
  36.     return a + b;
  37. }
  38.  
  39. int main()
  40. {
  41.     cout << GreatestCommonDivisor(10, 15);
  42.     return 0;
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement