【问题标题】: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试图制作一个函数来判断一个数字是否是素数。我做错什么了?我所有的测试都通过了,但是一个 edabit.com 测试失败了
【发布时间】:2023-04-04 18:49:01
【问题描述】:

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

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;
    }
}

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

【问题讨论】:

  • 哪个测试失败了?
  • x = 1 不是 素数,但 isPrime 返回 true

标签: c# algorithm primes


【解决方案1】:

通常,这是一个失败的边界案例。在您的实现中,它是1,它不是素数,但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;
    ...  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多