c#学习

c# 筛选法求素数

2019-03-03  本文已影响0人  李药师_hablee

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("请输入一个正整数,将求取该整数内的素数: ");
            string n = Console.ReadLine();
            int num = Convert.ToInt32(n);

            bool[] IsPrime = new bool[num + 1];//方便后面置为true

            for(int i=2;i<=num;i++)
            {
                IsPrime[i] = true;
            }

            for(int i=2;i<num;i++)
            {
                if(IsPrime[i])
                {
                    for(int j=i*2;j<=num;j=j+i)
                    {
                        IsPrime[j] = false;
                    }
                }
            }
            int count = 0;
            for(int i=2;i<=num;i++)
            {
                if(IsPrime[i])
                {
                    Console.Write($"{i}\t");
                    count++;
                    if(count%5==0)
                    {
                        Console.WriteLine();
                    }
                }
            }
        }
    }
}

输出

捕获.PNG
上一篇 下一篇

猜你喜欢

热点阅读