Prime Number Verifier Code Blocks 使我在 C# 中转换问题

Prime Number Verifier Code Blocks resturns me converting problems in C#

static void Main(string[] args)
        {
            if (isPrimeNumber(6))
            {
                Console.WriteLine("This is prime number");  
            }
            else
            {
                Console.WriteLine("This is not prime number");
            }
            Console.ReadLine();
        }
 

        private static bool isPrimeNumber(int number)
        {
            bool result = true;
            for (int i = 0; number - 1; i++)
            {
                if (number % i == 0)
                {
                    result = false;
                    i = number;
                }

            }
            return result;
        }

嘿!我的代码块中有一个关于质数验证的问题。这个程序 returns 我在 for 循环中:无法将类型“int”转换为“bool”。我该如何解决?我怎么了?

for (int i = 0; number - 1; i++) 应该是 for (int i = 0; i < number; i++) number - 1 不是布尔表达式。

private static bool isPrimeNumber(int number)
{
    bool result = true;
    for (int i = 2; i < number; i++)
    {
        if (number % i == 0)
        {
            result = false;
            i = number;
        }

    }
    return result;
}

我修好了 for (int i = 0; i < number; i++) 应该是 for (int i = 2; i < number; i++)

你有逻辑错误,看

 //typo: should be i < number - 1 instead of number - 1
 for (int i = 0; i < number - 1; i++)
 {
     if (number % i == 0) // <- always true, when i == 1
     {
         result = false;  // <- result == false whenever number >= 2 
         i = number;
     }
 }

每当 i == 1 然后 number % i == 0 并且你有 result = false。 让我们从头开始实施 isPrimeNumber

 private static bool isPrimeNumber(int number) {
   // 0, 1 and negative numbers are not prime
   if (number <= 1)
     return false;

   // we have just one even prime number, it's 2 
   if (number % 2 == 0)
     return number == 2;  

   // if we have a non-trivial divisors, the minimal one
   // is at most Sqrt(number)
   // (int) (...+1) - to be on the safe side in case of rounding errors
   int maxDivisor = (int)(Math.Sqrt(number) + 1);

   // Now we check divisor = 3, 5, 7, ..., maxDivisor
   for (int divisor = 3; divisor <= maxDivisor; divisor += 2)
     if (number % divisor == 0)
       return false;

   // All tests passed, number is prime
   return true;
 }