我正在尝试在Project Euler中执行problem 12。F中的列表处理问题#
numDivisor64是计算除数的数量。
我写这篇F#代码:
let problem12 =
{1L..300000L} |> Seq.map (fun x->x*(x+1L)/2L) |> Seq.map numDivisor64 |> Seq.filter (fun x->x>500L)
这道题找到了数量,而不是它的除数#。除了用不太紧凑的方式使用循环或递归来写这个,任何漂亮的方法?
另一个问题,我偶尔会发现,我需要通过向所有数字加上'L'来将32位int代码版本转换为64位版本。有没有办法避免这种情况?任何像C++模板?
我第一次写
let numDivisor n =
let rec countd n d =
if n%d=0 then
let n2, cnt = countd (n/d) d
n2, cnt+1
else
n, 0
let rec collect n d =
if n < d then 1
elif n%d=0 then
let n2, cnt = countd n d
(cnt+1) * (collect n2 d)
else
collect n (d+1)
collect n 2
后来我发现我需要更大的整数:
let numDivisor64 n =
let rec countd n d =
if n%d=0L then
let n2, cnt = countd (n/d) d
n2, cnt+1L
else
n, 0L
let rec collect n d =
if n < d then 1L
elif n%d=0L then
let n2, cnt = countd n d
(cnt+1L) * (collect n2 d)
else
collect n (d+1L)
collect n 2L
与Haskell不同,数字文字(如1)在F#中具有特定类型(在本例中为int = System.Int32),因此仅给该函数提供不同的签名将不起作用。解决方案是使用用户定义的数字文字类型,就像在cfern的文章中一样。当然是 – kvb 2009-12-10 13:55:43
。谢谢(你的)信息。 – barkmadley 2009-12-11 00:29:39