[英]Prime number check
I'm having some issues with my prime number checker in F#. 我在F#中的质数检查器遇到一些问题。 It doesn't seem to give the right results so I'm guessing I've screwed up the logic somewhere but I can't figure out where. 它似乎没有给出正确的结果,所以我猜我已经在某个地方搞砸了逻辑,但我不知道在哪里。 The implementation is a simple brute forcing one so the logic isn't complicated and I've implemented similiar solutions using for loops in imperative languages before. 该实现是一种简单的强制执行,因此逻辑并不复杂,我之前已经在命令式语言中使用for循环实现了类似的解决方案。
let rec isPrime iterator (n : int) =
match iterator with
| 1 -> isPrime (iterator + 1) n
| a when a = n -> isPrime (iterator + 1) n
| _ -> match n % iterator = 0 with
| true -> false
| false -> isPrime (iterator + 1) n
As you already figured out in the comments, the problem is that the function should terminate and say true
when the iterator reaches n
. 正如您已经在注释中指出的那样,问题在于该函数应该终止,并且在迭代器达到n
时说成true
。 You can actually make it faster just by iterating up to square root of n
or at least n/2
because by the time you reach n/2
, you know it will be a prime. 实际上,仅通过迭代n
平方根或至少n/2
即可使速度更快,因为到n/2
,您就知道它将是质数。
This kind of logic seems to be easier to write using if
rather than match
- although you can easily fix it by fixing the case in match
, I'd probably write something like: 使用if
而不是match
这种逻辑似乎更容易编写-尽管您可以通过在match
固定大小写来轻松修复它,但我可能会写类似:
let rec isPrime iterator (n : int) =
if iterator = n / 2 then true
elif iterator = 1 then isPrime (iterator + 1) n
elif n % iterator = 0 then false
else isPrime (iterator + 1) n
Also, you might not want to expose the iterator
parameter to the user - you can write the code using a nested function which calls the loop starting with iterator = 2
(and then you don't need the iterator = 1
case at all): 此外,您可能不想向用户公开iterator
参数-您可以使用嵌套函数编写代码,该函数调用以iterator = 2
开头的循环(然后根本不需要iterator = 1
情况):
let isPrime (n : int) =
let rec loop iterator =
if iterator = n/2 then true
elif n % iterator = 0 then false
else loop (iterator + 1)
loop 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.