I want to display prime numbers through a button from a LISTBOX to a textbox. The Interface displays properly prime numbers but only from 1 to 10, after that the algorithm changes and shows non prime values as prime values such as 44.
private void primnr()
{
int n = listBox1.Items.Count;
bool prim = true;
for (int i = 2; i < n; i++)
{
for (int j = 2; j <n; j++)
{
if (i!=j && i%j==0)
{
prim = false;
break;
}
}
if (prim)
{
textBox2.Text = textBox2.Text + "Numar prim: " + listBox1.Items[i].ToString() + Environment.NewLine;
}
prim = true;
}
}
Your algorithm is good, despite it's not necessary for j to go further than half the value of i. https://dotnetfiddle.net/ZafFsb prints:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
So I would say your issue are the values stored in listBox1.Items[i]
, make sure Items[43] = 43
? Attach a breakpoint and inspect the values.
Let's split the problem in two : generating prime numbers (logics), and displaying them to TextBox
(UI):
private static IEnumerable<int> Primes() {
yield return 2;
yield return 3;
List<int> primes = new List<int>() {3};
for (int value = 5; ; value += 2) {
int n = (int) (Math.Sqrt(value) + 0.5); // round errors for perfect squares
foreach (int divisor in primes) {
if (divisor > n) {
primes.Add(value);
yield return value;
break;
}
else if (value % divisor == 0)
break;
}
}
}
Now, it seems you want to get items of the list with prime indexes, ie
listBox1.Items[2], listBox1.Items[3], listBox1.Items[5],..., listBox1.Items[101], ...
You can query Primes()
with a help of Linq
using System.Linq;
...
var results = Primes()
.Take(index => index < listBox1.Count)
.Select(index => $"Numar prim: {listBox1.Ites[index]}");
// Time to Join results into a single string
textBox2.Text = string.Join(Environment.NewLine, results);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.