I'm trying to get all the factors of a number provided by a user and after a button click displaying all the factors on a MessageBox.
This is what my code code taken from Getting Factors of a Number answer by Mark Byers looks like, I thought I was pretty close, but I'm displaying the number of factors not the actual factor numbers.
For example if the user types in 10 and uses a button click, the MessageBox displays the number 4, but i'm wanting it to display the actual factors of 10 which should be 1,2,5,10.
*how can I display the factors?
public int Divisors(int fact)
{
int number = int.Parse(textBox2.Text);
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(number));
for (int i = 1; i < sqrt; i++)
{
if (number % i == 0)
{
factorCount += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrt * sqrt == number)
{
factorCount++;
}
return factorCount;
}
private void ShowallButton_Click(object sender, EventArgs e)
{
int input = int.Parse(textBox2.Text);
double output = Divisors(input);
MessageBox.Show(+output + "");
}