Skip to content

Instantly share code, notes, and snippets.

@deepyes02
Last active June 4, 2021 15:33
Show Gist options
  • Save deepyes02/3e851e1d6e38325971b443ffdc9eed62 to your computer and use it in GitHub Desktop.
Save deepyes02/3e851e1d6e38325971b443ffdc9eed62 to your computer and use it in GitHub Desktop.
calculate factorial of any given number as long as it is a positive whole number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial</title>
</head>
<body>
<h2>Find Factorial</h2>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method='POST'>
<label for="user_input">Enter a Number</label>
<input type="number" name="user_input" value=<?php echo isset($_POST['user_input']) ? $_POST['user_input'] : '' ?> />
<input type="submit" />
<br>
<?php if (isset($_POST['user_input'])) : ?>
<h5><?php echo factorial($_POST['user_input']) ?></h5>
<?php endif; ?>
</form>
<?php
/**
* Calculate and return factorial of any given number
* @param int $n - any valid number
* @return int - when input is valid
* @return string - when input is less than zero, i.e, negative
*/
function factorial(int $n)
{
# logic for when input is less than or equal to zero
if ($n <= 0) # return string invalid for number less than 0, and 1 for 0 and 1.
{
# returns invalid for negative number, and 1 for the rest of the possibility.
# because of the if ($n <= 0) block, the only possible conditionals are either negative or zero here.
return $n < 0 ? "Invalid, range is 0 ~ ..." : intval(1);
}
//validation ends, start the logic for valid whole numbers, e.g 4
# this block will keep a check on the function for the value of run
# and will execute when n is reduced to 1 by the following recursive function right after the code.
if ($n == 1) {
return $n;
}
#recursive function.
# smartly grabs the number and calls the function with one less, if not checked by if ($n == 1)
# this function will run indefinitely and cause fatal error
return $n * factorial(intval($n - 1));
}
?>
<script src="https://gist.github.com/deepyes02/3e851e1d6e38325971b443ffdc9eed62.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment