C# 判断一个整数是否是素数!使用bool IsPrim(int n)实现!

static void Main(string[] args)
        {

            string input = "";
            bool result;
            int number = 0;
            do
            {
                Console.WriteLine("请输入一个正整数:");
                input = Console.ReadLine();
                if (input=="q")
                {
                    Console.WriteLine("程序结束!");
                    break;
                }
                try
                {
                    number = Convert.ToInt32(input);
                    result = IsPrim(number);
                    if (result==true)
                    {
                        Console.WriteLine("{0}是素数!", number);
                    }
                    else
                    {
                        Console.WriteLine("{0}不是素数!",number);
                    }
                }
                catch
                {
                    Console.WriteLine("输入数据有误,请重新输入!");
                    continue;
                }
            } while (true);
            Console.ReadKey();
        }
        public static bool IsPrim(int number)
        {
            for (int i = 2; i < number; i++)
            {
                if (number%2==0)
                {
                    return false;
                }
            }
            return true;
        }
        public static int ReadInt()
        {
            int number = 0;
            do
            {
                try
                {
                    number = Convert.ToInt32(Console.ReadLine());
                    if (number<=0)
                    {
                        Console.WriteLine("输入有误!请输入一个正数!");
                        continue;
                    }
                }
                catch
                {
                    Console.WriteLine("输入有误,请重新输入!");
                }
            } while (true);
        }

posted @ 2018-10-08 15:34  漂洋过海的鱼  阅读(1597)  评论(1编辑  收藏  举报