Last active
August 29, 2015 14:16
-
-
Save zaneli/0e735a1262af2e84b9de to your computer and use it in GitHub Desktop.
「HaskellでProject Euler(Problem 64~66)」ブログ用
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
import Data.List (unfoldr) | |
main = print $ length $ filter (odd . length . snd . sqrts) [1..10000] | |
sqrts :: Integer -> (Integer, [Integer]) | |
sqrts n | m^2 == n = (n, []) | |
| otherwise = (m, unfoldr f $ (1, -m, Nothing)) | |
where | |
m = truncate $ sqrt $ fromInteger n | |
f (x, y, Just z) | (x, y) == z = Nothing | |
f (x, y, z) = Just (q, (x', r-m, termCond z)) | |
where | |
x' = (n - (y^2)) `div` x | |
(q, r) = ((negate y)+m) `divMod` x' | |
termCond Nothing = Just (x, y) | |
termCond _ = z |
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
import Data.Ratio ((%), numerator) | |
import Zaneli.Euler (numToList) | |
main = print $ sum $ numToList $ numerator $ convergent $ map (%1) $ take 100 es | |
es :: [Integer] | |
es = 2:concatMap (\n -> [1, n, 1]) [2,4..] | |
convergent :: Fractional a => [a] -> a | |
convergent ns = foldr1 (\a b -> a + recip b) ns |
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
import Data.List (find, inits, maximumBy, unfoldr) | |
import Data.Maybe (mapMaybe) | |
import Data.Ord (comparing) | |
import Data.Ratio ((%), denominator, numerator, Ratio) | |
main = print $ fst $ maximumBy (comparing snd) $ mapMaybe f [1..1000] | |
where | |
f n = fmap (\p -> (n, numerator p)) (pell n) | |
pell :: Integer -> Maybe (Ratio Integer) | |
pell d = find isPell $ map convergent ns | |
where | |
isPell n = (numerator n)^2 - (denominator n)^2 * d == 1 | |
ns | null ms = [] | |
| otherwise = map (m:) $ tail $ inits $ cycle ms | |
where (m, ms) = sqrts d | |
sqrts :: Integer -> (Integer, [Integer]) | |
sqrts n | m^2 == n = (n, []) | |
| otherwise = (m, unfoldr f $ (1, -m, Nothing)) | |
where | |
m = truncate $ sqrt $ fromInteger n | |
f (x, y, Just z) | (x, y) == z = Nothing | |
f (x, y, xs) = Just (q, (x', r-m, termCond xs)) | |
where | |
x' = (n - (y^2)) `div` x | |
(q, r) = ((negate y)+m) `divMod` x' | |
termCond Nothing = Just (x, y) | |
termCond _ = xs | |
convergent :: Integral a => [a] -> Ratio a | |
convergent ns = foldr1 (\a b -> a + recip b) $ map (%1) ns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment