NWD¶
Opis problemu¶
Wersja z odejmowaniem¶
Algorytm Euklidesa - wersja iteracyjna¶
Algorytm Euklidesa - wersja rekurencyjna¶
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a = 32;
int b = 12;
int result = gcd(a, b);
cout << "gcd(" << a << "," << b << ") = " << result << endl;
return 0;
}
Operacje binarne - wersja iteracyjna¶
#include <iostream>
using namespace std;
int gcd(int a, int b) {
int shift;
if (a == 0) {
return b;
}
if (b == 0) {
return a;
}
for (shift = 0; ((a | b) & 1) == 0; shift++) {
a >>= 1;
b >>= 1;
}
while ((a & 1) == 0) {
a >>= 1;
}
while (b != 0) {
while ((b & 1) == 0) {
b >>= 1;
}
if (a > b) {
swap(a, b);
}
b = b - a;
}
return a << shift;
}
int main() {
int a = 32;
int b = 12;
int result = gcd(a, b);
cout << "gcd(" << a << "," << b << ") = " << result << endl;
return 0;
}