1. 計算及產生質數個數

namespace Q1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int n = int.Parse(textBox1.Text);
            List<int> all = new List<int>();
            for(int k = 2; k <= n; k++)
            {
                bool any = false;
                for (int i = 2; i <= Math.Sqrt(k); i++)
                {
                    if (k % i == 0)
                    {
                        any = true;
                        break;
                    }
                }
                if (!any)
                {
                    all.Add(k);
                }
            }
            a.Text = $"質數個數有  {all.Count}  個";
            b.Text = $"最大的三個質數是  {string.Join("  ", all.TakeLast(3))}";
        }
    }
}

Last updated