Files
c-contest/1. problem_rl/README.md
2026-01-29 21:11:51 +05:00

109 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Problem RL - рекурсия в цикл
Ниже приведён исходный код программы для рекурсивного алгоритма Евклида.
**Ваша задача**: переписать его так, чтобы вместо рекурсии использовался цикл
Посылка должна состоять из программы, считывающей со стандартного ввода два числа `x` и `y` и выводящей на стандартный вывод одно число `g`
## Пример 1
| Ввод | Вывод |
| --------------- | --------------- |
| `2 1` | `1` |
## Пример 2
| Ввод | Вывод |
| --------------- | --------------- |
| `3 2` | `1` |
## Пример 3
| Ввод | Вывод |
| --------------- | --------------- |
| `2 4` | `2` |
## Примечания
```c
#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;
}
```
# Решение
```c
#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;
}
```