mirror of
https://github.com/correl/euler.git
synced 2024-11-23 19:19:53 +00:00
Haskell 003
This commit is contained in:
parent
c1dc6c41b9
commit
09031a099d
1 changed files with 27 additions and 0 deletions
27
haskell/e003.hs
Normal file
27
haskell/e003.hs
Normal file
|
@ -0,0 +1,27 @@
|
|||
{-
|
||||
Find the largest prime factor of a composite number.
|
||||
|
||||
The prime factors of 13195 are 5, 7, 13 and 29.
|
||||
What is the largest prime factor of the number 600851475143 ?
|
||||
-}
|
||||
|
||||
import Text.Printf
|
||||
|
||||
pfactor :: (Integral a) => a -> [a]
|
||||
pfactor n = pfactor_ n []
|
||||
|
||||
pfactor_ :: (Integral a) => a -> [a] -> [a]
|
||||
pfactor_ n factors = do
|
||||
let next = pfactor_next n 2
|
||||
if next == n
|
||||
then factors ++ [n]
|
||||
else pfactor_ (n `div` next) (factors ++ [next])
|
||||
|
||||
pfactor_next :: (Integral a) => a -> a -> a
|
||||
pfactor_next n factor
|
||||
| n == factor = factor
|
||||
| n `rem` factor == 0 = factor
|
||||
| otherwise = pfactor_next n (factor + 1)
|
||||
|
||||
main = do
|
||||
printf "Largest prime factor of 600851475143: %d\n" (last (pfactor 600851475143) :: Int)
|
Loading…
Reference in a new issue