判断素数(C#)

来源:互联网 发布:nginx配置location详解 编辑:程序博客网 时间:2024/04/25 14:16

来源:北大青鸟C#作业题

描述:判断用户输入一个正整数是否是素数。

工具:Visual Studio 2005  (控制台程序)

Source:

using System;
using System.Collections.Generic;
using System.Text;

namespace P52_1
{
    class Program
    {
        static void Main(string[] args)
        {
            Cal a = new Cal();
            a.sushu();
        }
    }
    class Cal
    {
        private int c=0;
        string s;

        public int C
        {
            get
            {
                return c;
            }
            set
            {
                if (value <= 0)
                {
                    Console.WriteLine("请输入正数!");
                    return;
                }
                c = value;
            }
        }
        public void sushu()
        {
            Console.WriteLine("请输入一个正数:");
            do
            {
                s = Console.ReadLine();
                try
                {
                    C = Int32.Parse(s);
                }
                catch (Exception e)
                {
                    Console.WriteLine("请输入数字!");
                }
            } while (c <= 0);

            for (int i = 2; i < C; i++)
            {
                if (C % i == 0)
                {
                    Console.WriteLine("您输入的正数{0}不是素数,第一个整除的数是{1}", C, i);
                    return;
                }
            }
            Console.WriteLine("您输入的正数{0}是素数。", C);

        }
    }
}