Kalkulator NWD z krokami
Algorytmy z egzaminu różnymi sposobami - JavaScript od podstaw: konsola (HTML/CSS/JS)
Formularz liczy NWD algorytmem z resztą i pokazuje każdy krok jako element listy `<ol>` (nowy `li` na każdy obrót pętli). Przed liczeniem lista jest czyszczona (`replaceChildren()`), a dane są sprawdzane: obie liczby muszą być całkowite i dodatnie. Model i widok są znowu rozdzielone: funkcja `gcdSteps` zwraca wynik i listę kroków, strona tylko je wyświetla.
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<title>Kalkulator NWD</title>
<style>
body { font-family: sans-serif; max-width: 34em; }
#grid { display: grid; grid-template-columns: repeat(10, 2.4em); gap: 4px; }
#grid div { border: 1px solid #94a3b8; text-align: center; padding: 0.3em 0; cursor: pointer; }
#grid .prime { background: #dcfce7; color: #166534; font-weight: bold; }
input, button { font: inherit; padding: 0.3em; }
.error { color: #b91c1c; }
</style>
</head>
<body>
<h1>NWD algorytmem Euklidesa</h1>
<input id="a" type="number" value="48"> i <input id="b" type="number" value="18">
<button id="run">Licz</button>
<p id="result"></p>
<ol id="steps"></ol>
<script>
function gcdSteps(a, b) {
const steps = [];
while (b !== 0) {
steps.push(`${a} % ${b} = ${a % b}`);
[a, b] = [b, a % b];
}
return { value: a, steps };
}
document.getElementById('run').addEventListener('click', () => {
const a = Number(document.getElementById('a').value);
const b = Number(document.getElementById('b').value);
const list = document.getElementById('steps');
const result = document.getElementById('result');
list.replaceChildren();
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 1 || b < 1) {
result.textContent = 'Podaj dwie dodatnie liczby całkowite.';
return;
}
const { value, steps } = gcdSteps(a, b);
for (const text of steps) {
const li = document.createElement('li');
li.textContent = text;
list.appendChild(li);
}
result.textContent = `NWD(${a}, ${b}) = ${value}`;
});
</script>
</body>
</html>Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.