How to Develop a GCD Calculator with HTML and JavaScript: A Step-by-Step Guide

 In this blog post, we'll show you how to develop a GCD (Greatest Common Divisor) calculator using HTML and JavaScript. This calculator can help you find the largest positive integer that divides two given numbers without leaving a remainder. 

Photo by Antoine Dautry on Unsplash

What is a GCD ?

The greatest common divisor (gcd) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers without leaving a remainder. In other words, the gcd is the highest number that both integers can be divided by evenly. It is denoted as gcd(x,y) for two integers x and y, and it is commonly used in many mathematical calculations and applications, such as simplifying fractions, finding common factors, and solving equations.

Development of GCD calculator 

Setting up the HTML form

To create a GCD calculator, we need an HTML form that takes two input values (the two numbers to find the GCD of) and a button to trigger the calculation. Here's the HTML code for the form:

<form class="container">
  <div class="form-group my-4">
    <label for="">Enter 1st number</label>
    <input type="number" class="form-control" placeholder="1st no" id="FirstNo" required>
  </div>
  <div class="form-group">
    <label for="">Enter 2nd number</label>
    <input type="number" class="form-control" placeholder="2nd no" id="SecondNo" required>
  </div>
  <button type="submit" class="btn btn-outline-secondary text-light cal">Calculate</button>
</form>
<p class="text-center my-3 mb-3" id="ans"></p>

We've used Bootstrap classes to style the form. This form includes two input fields for taking user inputs and a button to submit the form. We have also created an empty paragraph with an ID of "ans" to display the result.

Writing the JavaScript Code:

Now that we have created the HTML form, it's time to write the JavaScript code to evaluate the prefix expression and calculate the result. You can write this JavaScript in script tag within same html file or can create different js file & link that js in html file. Here is the full code:

$('.cal').click(function (e) {
  var n1 = document.getElementById('FirstNo').value;
  var n2 = document.getElementById('SecondNo').value;
  var hcf;
  if ((n1 == "") || (n2 == "") || (n1 == "" && n2 == "")) {
    document.getElementById('ans').innerHTML = "Enter input";
  }
  else {
    for (let i = 1; i <= n1 && i <= n2; i++) {
      // check if is factor of both integers
      if (n1 % i == 0 && n2 % i == 0) {
        hcf = i;
      }
    }
    document.getElementById('ans').innerHTML = "GCD of " + n1 + " & " + n2 + " is  " + '<h4 class="text-danger" >' + hcf + '</b>';
  }
  e.preventDefault();
});

 Breaking down this code into snippets with it's step by step explanation:

  1. First, we're targeting the button with class .cal and adding a click event listener to it using jQuery's .click() function.And have added e.preventDefault() function to prevent page reload:
  2.   $(".cal").click(function (e) {
          e.preventDefault();
    });
    
  3. Following lines of code create three variables. The first two variables, n1 and n2, get the value of the HTML input elements with ids 'FirstNo' and 'SecondNo', respectively. The third variable, hcf, is initialized to undefined. :
  4. var n1 = document.getElementById('FirstNo').value;
    var n2 = document.getElementById('SecondNo').value;
    var hcf; 
  5. Below code block checks whether both input fields have been filled out. If either field is empty, or both fields are empty, the program prints an error message to the HTML element with id 'ans'. If both fields have values, the code to find the GCD is executed:
  6. if ((n1 == "") || (n2 == "") || (n1 == "" && n2 == "")) {
      document.getElementById('ans').innerHTML = "Enter input";
    }
    else {
      // code to find GCD goes here
    } 
  7. This for loop iterates from 1 up to the smaller of n1 and n2. For each iteration, it checks whether the current number is a factor of both n1 and n2. If it is, it assigns the current number to the hcf variable. :
  8. for (let i = 1; i <= n1 && i <= n2; i++) {
      if (n1 % i == 0 && n2 % i == 0) {
        hcf = i;
      }
    
  9. We're looping through the `prefixExp` variable from the end to the beginning using a for loop. And Inside it, we're checking if the current character is a digit using the `is_numeric()` function. If it is, we're pushing it onto the stack array :
  10. for (idx = prefixExp.length - 1; idx >= 0; idx--) {
      if (is_numeric(parseInt(prefixExp[idx]))) {
      stack.push(prefixExp[idx]);
      }
    }
  11. This line of code prints the GCD to the HTML element with id 'ans'. The GCD is a concatenation of the strings "GCD of ", n1, " & ", n2, " is ", and the value of hcf. The value of hcf is wrapped in an HTML tag to give it a red color.:
  12. document.getElementById('ans').innerHTML = "GCD of " + n1 + " & " + n2 + " is  " + '<h4 class="text-danger" >' + hcf + '</b>';
Here's how the calculator looks after some CSS modifications and using built-in Bootstrap classes. You can see a screenshot of the updated design below and test it using this link.

CalConT


You can checkout how I developed this calculator in calcont's github repo & contribute to it as well.

Hope you got the idea for developing GCD calculator using html & javascript, Thanx !!

Post a Comment

0 Comments