In: Computer Science
Utilizing PHP and HTML code
Create a form that has text inputs for two numbers and a submit button. Submit the values to a program that calculates and displays the GCD of the two numbers. The greatest common divisor of two integers a and b is the largest integer that is a factor of both a and b.
The GCD of any number and 1 is 1, and the GCD of any number and 0 is that number.
For example:
gcd(24, 84) =12,
gcd(105, 45) =15,
gcd(409, 1) = 1,
and gcd(0, 8) =8.
You could set up a loop for each number and find all the factors using the modulo operator. Then you could compare the two lists of factors and find the largest number they have in common. This would work but it is going to be slow for very large numbers.
One efficient way to compute the GCD is to use Euclid's Algorithm, which states the following:
gcd(a, b) = gcd(b, a % b)
gcd(a, 0) = Absolute value of a
Here is an example of using this algorithm for 154,320 and 4,320
Looks like it would be perfect for a while loop.
1. Install xampp
2. Make folder in htdocs in xampp in c drive. Save this code with name index.php in that folder.
3.On xampp control pannel open phpMyadmin using apache admin button.
4. open this file in the server
index.php
<?php //php code starts here
if(isset($_POST['num1']) && isset($_POST['num2'])) {
// If isset then assign data to variable $name = $_POST['num1]
$num1 = $_POST['num1']; //$_POST is global varible
$num2 = $_POST['num2']; //$_POST['num1'] pr $_POST['num2'] grabs the form element with name num1/num2.
function calcGcd(int $num1, int $num2) {
if($num1 == 0)
return $num2;
return calcGcd($num2 % $num1, $num1);
}
echo "GCD of ".$num1." and ".$num2.": ".calcGcd($num1, $num2)."<br><br>"; //calling calcGCD() function
} else {
//redirect to error page
//header('location: index.php');
}
//php code ends here
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="index.php" method="post" name="form1">
Number_1 <input type="text" name="num1"><br><br>
Number_2 <input type="text" name="num2"><br><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Output1:
before entering the numbers
Output 2:
After entering the numbers