繁体   English   中英

试图制作一个 function 来判断一个数字是否为质数。 我做错了什么? 我所有的测试都通过了,但是一个 edabit.com 测试失败了

[英]Trying to make a function to tell is a number is prime or not. What did I do wrong? All my tests pass, but one edabit.com test failed

这是用于确定它是否是质数的代码。 请告诉我我做错了什么。

public class Program
{
    public static bool isPrime(int x)
    {
            int i = 2;

            while (i < x)
            {
                double divided = ((double) x / (double) i);

                if (divided % 1 == 0)
                {
                    return false;
                }

                i++;
            }

            return true;
    }
}

许多测试中只有一个失败了,所以我确信这是一些模糊的边缘情况。

通常,这是一个失败的边界案例 在您的实现中,它1不是 prime ,但isPrime(1)返回true 您可以在Linq的帮助下测试例程:

using System.Linq;

...

private static bool IsIntPrime(int value) {
  if (value <= 1)
    return false;
  else if (value % 2 == 0)
    return value == 2;

  int n = (int)(Math.Sqrt(value) + 0.5);

  for (int i = 3; i <= n; i += 2)
    if (value % i == 0)
      return false;

  return true;
}

查询时间:

  var failedTests = Enumerable
    .Range(0, 100) // let's test [0..99] range
    .Select(x => new {
      x,
      expected = IsIntPrime(x),
      actual = isPrime(x)
    })
    .Where(item => item.actual != item.expected)
    .Select(item => $"{item.x,3} expected: {item.expected,5} actual: {item.actual,5}");

 Console.Write(string.Join(Environment.NewLine, failedTests));

结果:

 0 expected: False actual:  True
 1 expected: False actual:  True

更正:

public static bool isPrime(int x)
{
    // All numbers which are less or equal to 1 are not primes
    if (x <= 1)
        return false; 

    int i = 2;
    ...  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM