我正在嘗試在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