C#求任意范围内的质数

    class Program
    {
        public static List<int> list;
        static void Main(string[] args)
        {
            Console.WriteLine("请输入下限:");
            int min = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("请输入上限:");
            int max = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(min+"-"+max + "以内的质数有:");
            GetZhi(min, max);
            foreach (int a in list)
            {
                Console.WriteLine(a);
            }
            Console.ReadLine();
        }

        public static void GetZhi(int min,int max)
        {
            list = new List<int>();
            if (min % 2 == 0)
                min = min + 1;
            for (int i = min; i <= max; i += 2)
            {
                bool a = true;
                for (int j = 3; j < i; j++)
                {
                    if (i % j == 0)
                    {
                        a = false;
                        break;
                    }
                }
                if (a)
                    list.Add(i); 
            }
        }
    }

 

 

posted @ 2013-06-21 17:12  爹子王  阅读(816)  评论(0编辑  收藏  举报