程序应要求一个数字,并打印介于1到用户输入的数字之间的所有质数...为什么不起作用?
bool isPrime = true;
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
答案 0 :(得分:3)
您已将布尔值置于循环之外。因此,一旦它为假,在其他循环中就永远不会为真,这会导致问题。
int primes = 0;
Console.WriteLine("Enter a number");
int N = int.Parse(Console.ReadLine());
for (int i = 2; i <= N; i++)
{
bool isPrime = true;
for (int j = 2; j <= Math.Sqrt(i); j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
if (isPrime)
{
Console.WriteLine(i + " is a prime number");
primes++;
}
}
Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers");
答案 1 :(得分:0)
首先定义此类:
public static class PrimeHelper
{
public static bool IsPrime(int candidate)
{
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
然后在您的应用程序中调用它:
var finalNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < finalNumber; i++)
{
bool prime = PrimeHelper.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}