top of page

Factors Algorithm

C# / Unity

using System.Globalization;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class FactorsCheck : 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))
            {
                //Get the list of factors
                List<int> factorList = CheckInput(intInput);
                //If check in case there's too many factors to display on screen
                if (factorList.Count < 20)
                {
                    //Create a list for string converstion
                    List<string> factorListConverted = new List<string>();
                    //Loop through the numbers and convert them to string, with correct format
                    foreach (int number in factorList)
                    {
                        factorListConverted.Add(number.ToString("#,##0"));
                    }
                    //Convert the list of ints to a string for display
                    string factors = string.Join(" | ", factorListConverted.ToArray());
                    //Display the original number + its factors
                    outputText.text = "The factors of '" + intInput.ToString("#,##0") + "' are: \n" + factors;
                }
                //Tell user there's too many factors
                else
                {
                    outputText.text = "There are too many factors to show.";
                }
            }
            //Tell user they didn't enter a number
            else
            {
                outputText.text = "No int (Number) was entered. \nOr int too large.";
            }

            //Reset input field
            textInputField.text = "";
        }
    }

    public List<int> CheckInput(int input)
    {
        //Declare variables to be used
        int remainderNum;
        //Creating list for output
        List<int> output = new List<int>();

        //Decrement copy of original number through the loop
        for(int i = input; i > 0; i--)
        {
            //Check if remainder is 0
            remainderNum = input % i;
            if(remainderNum == 0)
            {
                //Add the current iteration to the output list
                output.Add(i);
            }
        }
        return output;
    }
}

bottom of page