add task 2
This commit is contained in:
102
1. problem_rl/solution.c
Normal file
102
1. problem_rl/solution.c
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
/*
|
||||||
|
Problem RL -- рекурсия в цикл
|
||||||
|
|
||||||
|
Ниже приведён исходный код программы для рекурсивного алгоритма Евклида.
|
||||||
|
|
||||||
|
Ваша задача: переписать его так, чтобы вместо рекурсии использовался цикл
|
||||||
|
|
||||||
|
Посылка должна состоять из программы, считывающей со стандартного ввода два числа x и y и выводящей на стандартный вывод одно число g
|
||||||
|
|
||||||
|
Пример 1
|
||||||
|
|
||||||
|
Ввод: 2 1
|
||||||
|
Вывод: 1
|
||||||
|
|
||||||
|
Пример 2
|
||||||
|
|
||||||
|
Ввод: 3 2
|
||||||
|
Вывод: 1
|
||||||
|
|
||||||
|
Пример 3
|
||||||
|
|
||||||
|
Ввод: 2 4
|
||||||
|
Вывод: 2
|
||||||
|
|
||||||
|
Примечания
|
||||||
|
|
||||||
|
#include <assert.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
unsigned long long gcd(unsigned long long x,
|
||||||
|
unsigned long long y) {
|
||||||
|
unsigned long long q;
|
||||||
|
if (y > x)
|
||||||
|
return gcd(y, x);
|
||||||
|
assert (y > 0);
|
||||||
|
q = x % y;
|
||||||
|
if (q == 0)
|
||||||
|
return y;
|
||||||
|
return gcd(y, q);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
unsigned long long x = 0, y = 0, g;
|
||||||
|
int res;
|
||||||
|
|
||||||
|
res = scanf("%llu %llu", &x, &y);
|
||||||
|
assert(res == 2);
|
||||||
|
g = gcd(x, y);
|
||||||
|
printf("%llu\n", g);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <assert.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#define ull unsigned long long
|
||||||
|
#define ll long long
|
||||||
|
|
||||||
|
ull gcd_cycle(ll x, ll y);
|
||||||
|
ull gcd_recursive(ull x, ull y);
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
ull x = 0, y = 0, g;
|
||||||
|
int res;
|
||||||
|
|
||||||
|
res = scanf("%llu %llu", &x, &y);
|
||||||
|
assert(res == 2);
|
||||||
|
g = gcd_cycle(x, y);
|
||||||
|
printf("%llu\n", g);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
ull gcd_recursive(ull x, ull y) {
|
||||||
|
ull q;
|
||||||
|
if (y > x)
|
||||||
|
return gcd_recursive(y, x);
|
||||||
|
assert (y > 0);
|
||||||
|
q = x % y;
|
||||||
|
if (q == 0)
|
||||||
|
return y;
|
||||||
|
return gcd_recursive(y, q);
|
||||||
|
}
|
||||||
|
|
||||||
|
ull gcd_cycle(ll x, ll y) {
|
||||||
|
x = llabs(x);
|
||||||
|
y = llabs(y);
|
||||||
|
|
||||||
|
if (x == 0) return y;
|
||||||
|
if (y == 0) return x;
|
||||||
|
|
||||||
|
while (y != 0) {
|
||||||
|
ll r = x % y;
|
||||||
|
x = y;
|
||||||
|
y = r;
|
||||||
|
}
|
||||||
|
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user