![](https://static.wixstatic.com/media/d683fc_73505168a8754087811a83d8d6d1f09e~mv2.jpg/v1/fill/w_288,h_141,al_c,q_80,usm_0.66_1.00_0.01,blur_2,enc_auto/d683fc_73505168a8754087811a83d8d6d1f09e~mv2.jpg)
Factorial Algorithm
C# / Unity
using System.Globalization;
using UnityEngine;
using TMPro;
using System;
public class FactorialCheck : MonoBehaviour
{
public TextMeshProUGUI outputText;
private TMP_InputField textInputField;
private int intInput;
private void Start()
{
textInputField = GetComponent<TMP_InputField>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
//Check if a number was inputted or not
if (int.TryParse(textInputField.text, NumberStyles.Number, CultureInfo.CurrentCulture.NumberFormat, out intInput))
{
//Check if factorial is within reasonable bounds
if(intInput <= 20 && intInput >= -20)
{
outputText.text = "Factorial of '" + intInput.ToString() + "' is \n'" + CheckInput(intInput).ToString("#,##0") + "'";
}
//Tell user number is too large
else
{
outputText.text = "Factorial too large. \n(Try -20 - 20)";
}
}
//Tell user they didn't enter a number
else
{
outputText.text = "No int (Number) was entered.";
}
//Reset input field
textInputField.text = "";
}
}
//Using a long to handle slightly bigger factorials
public long CheckInput(int input)
{
//Get a long copy for computing
long outputNum = input;
//Determine if input is a positve or negative number
if (Math.Sign(outputNum) > 0)
{
//Decrement original value and compute factorial
for (int i = (input - 1); i > 0; i--)
{
outputNum *= i;
}
}
else
{
for (int i = (input + 1); i < 0; i++)
{
outputNum *= i;
}
}
//Return the computed number
return outputNum;
}
}