Haskell程式查詢完美數


在 Haskell 中,我們可以使用列表推導和暴力法來查詢完美數。

什麼是完美數?

完美數是等於其所有真因數之和的正整數。正整數 n 的因數是能整除 n 的正整數,沒有餘數。真因數是 n 的因數,且小於 n 本身。

例如,6 的真因數是 1、2 和 3,這些因數之和是 1 + 2 + 3 = 6。因此,6 是一個完美數。

演算法

  • 步驟 1 − 定義 perfectNumbers 函式

  • 步驟 2 − 程式執行將從 main 函式開始。main() 函式控制整個程式。它被寫成 main = do。在 main 函式中,傳遞了一個限制,在此限制下計算完美數。

  • 步驟 3 − 初始化名為“limit”的變數。它將儲存要計算完美數的整數上限。

  • 步驟 4 − 函式呼叫後,使用 ‘putStrLn’ 語句將結果列印到控制檯。

示例 1

在此示例中,列印了給定限制(在本例中為 1000)內的完美數。perfectNumbers 函式使用列表推導生成一個列表,其中包含所有小於等於限制的正整數,這些整數等於其真因數之和,由 properDivisors 函式確定。然後,main 函式計算完美數並將結果列印到控制檯。

perfectNumbers :: Int -> [Int]
perfectNumbers limit = [x | x <- [2..limit], x == sum (properDivisors x)]

properDivisors :: Int -> [Int]
properDivisors n = [x | x <- [1..n-1], n `mod` x == 0]

main :: IO ()
main = do
   let limit = 1000
   let perfects = perfectNumbers limit
   putStrLn $ "The perfect numbers up to " ++ show limit ++ " are: " ++ show perfects

輸出

The perfect numbers up to 1000 are: [6,28,496]

示例 2

在此示例中,使用埃拉托色尼篩法定義了 perfectNumbers 和 properDivisors 函式來計算完美數。

import Data.Array

properDivisors :: Int -> [Int]
properDivisors n = [x | x <- [1..n `div` 2], n `mod` x == 0]

perfectNumbers :: Int -> [Int]
perfectNumbers limit = [x | x <- [2..limit], x == sum (properDivisors x)]

main :: IO ()
main = do
   let limit = 1000
   let perfects = perfectNumbers limit
   putStrLn $ "The perfect numbers up to " ++ show limit ++ " are: " ++ show perfects

輸出

The perfect numbers up to 1000 are: [6,28,496]

示例 3

在此示例中,isPerfect 函式以整數 n 作為輸入,如果 n 是完美數則返回 True,否則返回 False。perfectNumbers 函式使用列表推導生成一個列表,其中包含所有小於等於限制的正整數,這些整數是完美數,由 isPerfect 函式確定。然後,main 函式計算完美數並將結果列印到控制檯。

isPerfect :: Int -> Bool
isPerfect n = n == sum [x | x <- [1..n-1], n `mod` x == 0]

perfectNumbers :: Int -> [Int]
perfectNumbers limit = [x | x <- [2..limit], isPerfect x]

main :: IO ()
main = do
   let limit = 1000
   let perfects = perfectNumbers limit
   putStrLn $ "The perfect numbers up to " ++ show limit ++ " are: " ++ show perfects

輸出

The perfect numbers up to 1000 are: [6,28,496]

結論

在 Haskell 中,我們可以使用一些使用者定義的函式以及 mod 函式或列表推導,或者使用暴力法來查詢一定限制內的完美數。

更新於: 2023年4月24日

332 次檢視

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告