haskell: add [p12, p17]

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-11-07 19:17:35 +05:30
parent 22fdf20500
commit de6ea02b14
7 changed files with 185 additions and 5 deletions

View File

@@ -1,19 +1,39 @@
module Lib (fib, primes, primeFactors) where
module Lib
( factors,
fib,
primes,
primeFactors,
sumOfDigits,
)
where
import Data.List (nub)
factors :: Integral a => a -> [a]
factors n = concat [if mod n f == 0 then nub [f, div n f] else [] | f <- [1 .. flsqrt n]]
fib :: [Integer]
fib = 1 : 2 : zipWith (+) fib (tail fib)
isPrime :: Integer -> Bool
isPrime n = n > 1 && null [[] | k <- [2 .. (floor $ sqrt $ fromIntegral n)], mod n k == 0]
flsqrt :: Integral a => a -> a
flsqrt n = floor $ sqrt $ fromIntegral n
isPrime :: Integral a => a -> Bool
isPrime n = n > 1 && null [[] | k <- [2 .. flsqrt n], mod n k == 0]
primes :: [Integer]
primes = 2 : filter isPrime [3, 4 ..]
primeFactors :: Integer -> [Integer]
primeFactors :: Integral a => a -> [a]
primeFactors n = genPrimeFactors n 2
where
genPrimeFactors :: Integer -> Integer -> [Integer]
genPrimeFactors :: Integral a => a -> a -> [a]
genPrimeFactors n c
| c * c > n = [n]
| mod n c /= 0 = genPrimeFactors n (c + 1)
| otherwise = c : genPrimeFactors (div n c) c
sumOfDigits :: Integral a => a -> a
sumOfDigits n
| n == 0 = 0
| otherwise = mod n 10 + sumOfDigits (div n 10)