首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表框到文本框中的质数

从列表框到文本框中的质数
EN

Stack Overflow用户
提问于 2020-04-11 01:33:00
回答 2查看 154关注 0票数 0

我想通过一个从LISTBOX到textbox的按钮来显示质数。该接口正确显示质数,但仅显示从1到10的质数,之后算法会更改并将非质数值显示为质数值,如44。

代码语言:javascript
复制
 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;
        }



    }
EN

回答 2

Stack Overflow用户

发布于 2020-04-11 02:21:48

你的算法很好,尽管j不需要超过i的一半。https://dotnetfiddle.net/ZafFsb打印:

代码语言:javascript
复制
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,

所以我想说你的问题是存储在listBox1.Items[i]中的值,确保Items[43] = 43?附加断点并检查值。

票数 0
EN

Stack Overflow用户

发布于 2020-04-11 03:09:38

让我们将问题一分为二:生成质数(逻辑),并将它们显示给TextBox (UI):

代码语言:javascript
复制
  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;  
      }
    }  
  }

现在,您似乎想要获取具有主索引的列表中的项,即

代码语言:javascript
复制
listBox1.Items[2], listBox1.Items[3], listBox1.Items[5],..., listBox1.Items[101], ...

你可以借助Linq查询Primes()

代码语言:javascript
复制
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);   
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61145564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档