Геометрический алгоритм Евклида позволяет найти наибольший общий делитель НОД. Напишем программу с Геометрическим алгоритмом Евклида и изучим цикл while.
Цикл while - это цикл с условием. Пока условие истинно тело цикла выполняется.
while (условие выполнения) { тело цикла; }
Программа нахождения наибольшего общего делителя с циклом while написана и проверена в IDE Geany.
#include <iostream> int x = 30855, y = 41514; int main() { while (x != y) { x > y ? x = x - y : y = y - x; } std::cout << "НОД = " << x << std::endl; return 0; }
Результат:
НОД = 561 ------------------ (program exited with code: 0) Press return to continue
Ещё один алгоритм Евклида с циклом while:
#include <iostream> int x = 30855, y = 41514; int main() { while (x % y != 0 && y % x != 0) { x > y ? x = x % y : y = y % x; } std::cout << "НОД = " << std::min(x, y) << std::endl; return 0; }
И тот же результат:
НОД = 561 ------------------ (program exited with code: 0) Press return to continue
На Arduino
С вычитанием:
unsigned int x = 30855,
y = 41514;
void setup() {
Serial.begin(9600);
int i = 0;
while (x != y) {
x > y ? x = x - y : y = y - x;
i++;
}
String rez = "Циклов " + String(i) + "\t" + "Ответ: " + String(x);
Serial.println(rez);
}
void loop() {
}
Результат
Циклов 13 Ответ 561
С делением по модулю:
unsigned int x = 30855,
y = 41514;
void setup() {
Serial.begin(9600);
int i = 0;
while (x % y != 0 && y % x != 0) {
x > y ? x = x % y : y = y % x;
i++;
}
String rez = "Циклов " + String(i) + "\t" + "Ответ: " + String(min(x, y));
Serial.println(rez);
}
void loop() {
}
Результат
Циклов 4 Ответ: 561
С циклом do ... while:
unsigned int x = 30855,
y = 41514;
void setup() {
Serial.begin(9600);
int i = 0;
do {
x > y ? x = x - y : y = y - x;
i++;
}
while (x != y);
String rez = "Циклов " + String(i) + "\t" + "Ответ: " + String(x);
Serial.println(rez);
}
void loop() {
}
Результат
Циклов 13 Ответ: 561