{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Μέγιστος Κοινός Διαιρέτης και Ελάχιστο Κοινό Πολλαπλάσιο" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Έστω ένα ορθογώνιο διαστάσεων x=30cm, y=12cm. Να βρεθεί ο μικρότερος αριθμός από τετράγωνα (ακέραιας πλευράς) που το καλύπτει." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Απάντηση: ΜΚΔ(30,12) = 6" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# μια απλοϊκή υλοποίηση\n", "def gcd_naive(x, y):\n", " z = min(x, y)\n", " for i in range(z, 0, -1):\n", " if x % i == 0 and y % i == 0:\n", " return i" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "13495" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# τυχαίες ακέραιες τιμές σε ένα διάστημα\n", "import random\n", "\n", "random.randrange(5000, 20000)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7.64 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], "source": [ "%%timeit \n", "# χρονομέτρηση απλοϊκού αλγορίθμου εύρεσης ΜΚΔ\n", "\n", "a = random.randrange(50000, 200000)\n", "b = random.randrange(50000, 200000)\n", "x = gcd_naive(a,b)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# ταχύτερος αλγόριθμος (αλγόριθμος του Ευκλείδη)\n", "def gcd(x, y):\n", " while y:\n", " x, y = y, x % y\n", " return x" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.9 µs ± 105 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n" ] } ], "source": [ "%%timeit\n", "\n", "a = random.randrange(50000, 200000)\n", "b = random.randrange(50000, 200000)\n", "\n", "x = gcd(a,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Αλγόριθμος του Ευκλείδη για την εύρεση του ΜΚΔ\n", "\n", "Πολυπλοκότητα: $\\mathcal{O}(\\log{(min(x,y))})$ \n", "\n", "https://www.baeldung.com/cs/euclid-time-complexity" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6 60.0\n" ] } ], "source": [ "# Ελάχιστο κοινό πολλαπλάσιο\n", "\n", "\n", "def lcm(x, y):\n", " return x * y / gcd(x, y)\n", "\n", "\n", "a, b = 30, 12\n", "print(gcd(a, b), lcm(a, b))" ] } ], "metadata": { "kernelspec": { "display_name": "py310", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }