top of page

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;
    }
}

bottom of page