Advertisement
Guest User

NWD

a guest
Dec 15th, 2022
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1.  
  2.     #include <vector>
  3.     #include <iostream>
  4.     using namespace std;
  5.  
  6. //  -------------------------   Deklaracje funkcji   -------------------------  //
  7.  
  8.     int nwd (int a, int b);
  9.  
  10. //  -------------------------   main   -------------------------  //
  11.  
  12. int main()
  13. {
  14.  
  15. //  -------------------------   Pobranie danych   -------------------------  //
  16.  
  17.     int  t  {};
  18.     cin >> t;
  19.  
  20.     vector <vector <int> > a;
  21.     a.resize(t);
  22.  
  23.     for (int i=0 ; i<t ; i++)
  24.     {
  25.         a[i].resize(2);
  26.         cin >> a[i][0];
  27.         cin >> a[i][1];
  28.     }
  29.  
  30. //  -------------------------   Szeregowanie danych   -------------------------  //
  31.  
  32.     int bufor {};
  33.  
  34.     for (int i=0 ; i<t ; i++)    //  Szeregujemy tablice.
  35.     {                            //  Wiekszy element rzedu ma byc na indeksie [i][0]
  36.         if ( a[i][1] > a[i][0] ) //  a mniejszy  -  [i][1]
  37.         {
  38.             bufor = a[i][0];
  39.             a[i][0] = a[i][1];
  40.             a[i][1] = bufor;
  41.         }
  42.     }
  43.  
  44. //  -------------------------   Wypisanie wynikow   -------------------------  //
  45.  
  46.     for (int i=0 ; i<t ; i++)
  47.     {
  48.         cout << nwd(a[i][0], a[i][1]);
  49.  
  50.         if (i<t-1) cout << endl;
  51.     }
  52.  
  53. //  -------------------------   Koniec   -------------------------  //
  54.  
  55. }
  56.  
  57. //  -------------------------   nwd()   -------------------------  //
  58.  
  59. int nwd (int a, int b)
  60. {
  61.     int rezultat {};
  62.     rezultat = b;     //  Wiemy juz, ze b <= a
  63.  
  64.     if ( (a % b) )      //  Jesli a dzieli sie przez b, pomin ponizszy blok.
  65.     {
  66.         if ( b % 2 == 0)  { b /= 2; rezultat = b; }   //  Najpierw sprobuj podzielic b przez 2.
  67.  
  68.         while((a % rezultat) or (b % rezultat))  //  Tak dlugo, az zarowno a jak i b nie beda
  69.         {                                        //  podzielne przez rezultat,
  70.             rezultat--;                          //  pomniejszaj rezultat.
  71.         }
  72.     }
  73.  
  74.     return rezultat;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement