The algorithm of C # judging prime number

Source: Internet
Author: User

A prime number is divisible only by 1 or itself, and cannot be the product of two other integers. 1, 2, 3 itself is prime, to determine whether a number is prime, just use this value divided by 2 to its root number, if there is a number divisible, then the value is not prime, return is prime. The code is as follows:

using System;
using System.Collections.Generic;
using System.Text;
namespace ExPrimeNumber
{
class PrimeNumber
{
public bool primeNumber(int n)
{
bool b = true;
if (n == 1 || n == 2)
b = true;
else
{
int sqr = Convert.ToInt32(Math.Sqrt(n));
for (int i = sqr; i > 2; i--)
{
if (n % i == 0)
{
b = false;
}
}
}
return b;
}
static void Main(string[] args)
{
Console.Write("请输入一个数:");
int n = Convert.ToInt32(Console.ReadLine ());
PrimeNumber p=new PrimeNumber ();
bool b=p.primeNumber(n);
if (b)
Console.WriteLine("{0}是素数",n);
else
Console.WriteLine("{0}不是素数",n);
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.