Advertisement
Guest User

NWD

a guest
Dec 14th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <math.h>
  4.  
  5. using namespace std;
  6.  
  7. string KonwertujDoLiczbyBinarnej(int n)
  8. {
  9.     string wynik="";
  10.     while(n!=1)
  11.     {
  12.         if(n%2==0)
  13.         {
  14.             wynik='0'+wynik;
  15.             n=n/2;
  16.         }
  17.         else
  18.         {
  19.             wynik='1'+wynik;
  20.             n=n/2;
  21.         }
  22.        
  23.     }
  24.     wynik='1'+wynik;
  25.     return wynik;  
  26. }
  27.  
  28. int KonwertujDoLiczbyDziesietnej(string n)
  29. {
  30.     int i,d=n.size(),s=0;
  31.     for(i=0;i<d;i++)
  32.     {
  33.         if(n[i]=='1')
  34.         {
  35.             s = s + pow(2, d-1-i);
  36.         }
  37.     }
  38.    
  39.     return s;
  40. }
  41.  
  42. int ZnajdzNWDEuklides(int n, int m)
  43. {
  44.     while(n != m){
  45.        if(n > m){
  46.            n = n - m;
  47.        }
  48.        else {
  49.            m = m - n;
  50.        }
  51.     }
  52.     return n;
  53. }
  54.  
  55. int main ()
  56. {
  57.      string a,b;
  58.      int n,m, liczbaTestow;
  59.      cout << "Podaj liczbe testow z przedzialu od 1 do 9" << endl;
  60.      cin >> liczbaTestow;
  61.      for(int i = 0; i < liczbaTestow; i++){
  62.          cout << "Podaj dwie liczby zapisane w systemie binarnym dla ktorych chcesz wyznaczyc NWD" << endl;
  63.          cin>>a>>b;
  64.          n=KonwertujDoLiczbyDziesietnej(a);
  65.          m=KonwertujDoLiczbyDziesietnej(b);
  66.          cout << "NWD(" << a << ", " << b << ")= " << KonwertujDoLiczbyBinarnej(ZnajdzNWDEuklides(n, m)) << endl;  
  67.      }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement