Skip to content

Instantly share code, notes, and snippets.

@hrlou
Created April 21, 2021 19:55
Show Gist options
  • Save hrlou/373f211ce47bdb333a7c660dce31094c to your computer and use it in GitHub Desktop.
Save hrlou/373f211ce47bdb333a7c660dce31094c to your computer and use it in GitHub Desktop.
gets perfect numbers
-- usage
-- quitegood test_size tolerance
import System.Environment
import Data.List
getDivisors :: Int -> [Int]
getDivisors n =
(1:) $ nub $ concat [ [x, div n x] | x <- [2..limit], rem n x == 0 ]
where limit = (floor.sqrt.fromIntegral) n
isPerfect :: Int -> Int -> Bool
isPerfect num tol = do
let val = (sum $ getDivisors num)
if val - num >= -tol && val - num <= -tol
then True else False
main :: IO()
main = do
args <- getArgs
let size = (abs $ read $ head args :: Int)
let tolerance = (abs $ read $ last args :: Int)
print [n | n <- [2..(size)], isPerfect n tolerance]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment