-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindefinite.html
63 lines (55 loc) · 2.1 KB
/
indefinite.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Large Numbers</title>
</head>
<body>
<h1>Add Two Large Numbers</h1>
<form id="numberForm">
<label for="num1">Enter the first number:</label>
<input type="text" id="num1" name="num1" required>
<br><br>
<label for="num2">Enter the second number:</label>
<input type="text" id="num2" name="num2" required>
<br><br>
<button type="submit">Add Numbers</button>
</form>
<div id="result"></div>
<script>
function addLargeNumbers(num1, num2) {
// Make sure num1 is the longer number
if (num1.length < num2.length) {
[num1, num2] = [num2, num1];
}
// Reverse both numbers
num1 = num1.split('').reverse().join('');
num2 = num2.split('').reverse().join('');
let carry = 0;
let result = [];
// Add each digit
for (let i = 0; i < num1.length; i++) {
const digit1 = parseInt(num1[i], 10);
const digit2 = i < num2.length ? parseInt(num2[i], 10) : 0;
const sum = digit1 + digit2 + carry;
carry = Math.floor(sum / 10);
result.push(sum % 10);
}
// If there's a carry left after the last addition
if (carry) {
result.push(carry);
}
// Reverse the result array and join it into a string
return result.reverse().join('');
}
document.getElementById('numberForm').addEventListener('submit', function(event) {
event.preventDefault();
const num1 = document.getElementById('num1').value;
const num2 = document.getElementById('num2').value;
const sum = addLargeNumbers(num1, num2);
document.getElementById('result').innerText = `Sum: ${sum}`;
});
</script>
</body>
</html>