Created
February 21, 2018 23:37
-
-
Save mlms13/280f984ee24bff3ebe770a66826f2372 to your computer and use it in GitHub Desktop.
Find Perfect Numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- http://www.mrpowell.net/progra/javascript/project4/project4.htm | |
-- A perfect number is a number where the sum of all the divisors is equal to two times the number. For example. | |
-- The divisors of the number 6 are 1, 2 , 3 and 6. 2 times 6 is 12. | |
-- 2 * 6 = 1 + 2 + 3 + 6 | |
-- Write a Java script program which will output the first nine perfect numbers. | |
import Data.Foldable (fold, sum) | |
import Data.List (List(..), (:), range, filter, reverse) | |
import Data.Int (toNumber) | |
import Math ((%)) | |
divisors :: Int -> List Int | |
divisors n = | |
filter (\d -> (toNumber n) % (toNumber d) == 0.0) $ range 1 n | |
isPerfect :: Int -> Boolean | |
isPerfect n = | |
(2 * n) == sum (divisors n) | |
perfects :: List Int | |
perfects = | |
go Nil 1 | |
where | |
-- Yeahhh... this whole thing is O(n^2) or worse, so good luck finding more than 4 | |
go :: List Int -> Int -> List Int | |
go list@(a : b : c : d : Nil) _ = | |
list | |
go soFar curr = | |
let l = if isPerfect curr then (curr : soFar) else soFar | |
in | |
go l (curr + 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment