检查数量为素数 [英] Check if number is prime number
问题描述
我只想问,如果这是检查的正确方式,如果数是素或不?因为我读了0和1不是质数。
INT NUM1;Console.WriteLine(接受数字:);
NUM1 = Convert.ToInt32(到Console.ReadLine());
如果(NUM1 == 0 || NUM1 == 1)
{
Console.WriteLine(NUM1 +不是质数);
到Console.ReadLine();
}
其他
{
对于(int类型的= 2; A< = NUM1 / 2; A ++)
{
如果(NUM1%一== 0)
{
Console.WriteLine(NUM1 +不是质数);
返回;
} }
Console.WriteLine(NUM1 +是一个素数);
到Console.ReadLine();
}
INT NUM1;Console.WriteLine(接受数字:);
NUM1 = Convert.ToInt32(到Console.ReadLine());
如果(isPrime(NUM1))
{
Console.WriteLine(这是黄金);
}
其他
{
Console.WriteLine(这不是素数);
}公共静态布尔isPrime(INT数)
{
INT边界=(int)的Math.Floor(的Math.sqrt(号)); 如果(数字== 1)返回false;
如果(编号== 2)返回true; 的for(int i = 2; I< =边界; ++ I){
如果(编号%我== 0)返回false;
} 返回true;
}
我改变了号/ 2
到的Math.sqrt(数字)
,因为从的的维基百科 的,他们说:
这个程序包括把 N 每个整数的 M 的较大
小于1且小于或等于平方根的n 。如果结果
任何这些部门是一个整数,然后点击 N 是不是素,
否则它是一个素数。事实上,如果 N = A * B 是复合材料(A和B≠
1),然后因素之一 或乙就一定是最多的平方的n根
块引用>I would just like to ask if this is a correct way of checking if number is prime or not? because I read that 0 and 1 are NOT a prime number.
int num1; Console.WriteLine("Accept number:"); num1 = Convert.ToInt32(Console.ReadLine()); if (num1 == 0 || num1 == 1) { Console.WriteLine(num1 + " is not prime number"); Console.ReadLine(); } else { for (int a = 2; a <= num1 / 2; a++) { if (num1 % a == 0) { Console.WriteLine(num1 + " is not prime number"); return; } } Console.WriteLine(num1 + " is a prime number"); Console.ReadLine(); }
解决方案int num1; Console.WriteLine("Accept number:"); num1 = Convert.ToInt32(Console.ReadLine()); if(isPrime(num1)) { Console.WriteLine("It is prime"); } else { Console.WriteLine("It is not prime"); } public static bool isPrime(int number) { int boundary = (int)Math.Floor(Math.Sqrt(number)); if (number == 1) return false; if (number == 2) return true; for (int i = 2; i <= boundary; ++i) { if (number % i == 0) return false; } return true; }
I changed
number / 2
toMath.Sqrt(number)
because from in wikipedia, they said:This routine consists of dividing n by each integer m that is greater than 1 and less than or equal to the square root of n. If the result of any of these divisions is an integer, then n is not a prime, otherwise it is a prime. Indeed, if n = a*b is composite (with a and b ≠ 1) then one of the factors a or b is necessarily at most square root of n
这篇关于检查数量为素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!