Reputation: 109
I tried running this code in visual studio. It doesn't output anything and runs infinite loop.
private void calculateButton_Click(object sender, EventArgs e)
{
int startNumber, endNumber, counter, num;
startNumber = Convert.ToInt32(minValue.Text);
endNumber = Convert.ToInt32(maxValue.Text);
int startNumCounter = startNumber;
for (num = startNumCounter; num <= endNumber; num++)
{
counter = 0;
int numCurrent = num;
for (int i = 2; i <= num; i++)
{
if (numCurrent % i == 0)
{
output.Text += " " + i + " ";
num = num / i;
counter++;
}
if (counter != 0 && num >= 2)
output.Text = "Factors: " + num;
}
}
}
}
}
Expected output: Min 7, Max: 10 ...... 8: 2 * 2 * 2. 9: 3 * 3. 10: 2 * 5. So it finds prime factors of numbers within min and max range. If the numbers inside the range are primes it doesn't count prime factor for.
Upvotes: 0
Views: 115
Reputation: 830
This is the code I came up with:
private void calculateButton_Click(object sender, EventArgs e)
{
int startNumber, endNumber, counter, num;
startNumber = Convert.ToInt32(minValue.Text);
endNumber = Convert.ToInt32(maxValue.Text);
int startNumCounter = startNumber;
for (num = startNumCounter; num <= endNumber; num++)
{
output.Text += $"Factors {num}:";
counter = 0;
int numCurrent = num;
for (int i = 2; i <= numCurrent; i++)
{
bool continueToNexti = false;
while (!continueToNexti)
{
if (numCurrent % i == 0)
{
output.Text += $" {i} ";
numCurrent = numCurrent / i;
counter++;
}
else
{
continueToNexti = true;
}
}
}
output.Text += Environment.NewLine;
}
}
Some notes on this: The reason your code didn't end is that this line
num = num / i;
which should have been
numCurrent = numCurrent / i;
Furthermore I came up with an extra loop, the While loop, to account for the fact that a number may be dividable by the same factor multiple times.
And to speed things up a bit, I changed
for (int i = 2; i <= num; i++)
to
for (int i = 2; i <= numCurrent; i++)
Upvotes: 1