Permalink
Browse files

add a solution to 58 that runs reasonably quickly (32 seconds for me)

  • Loading branch information...
1 parent 1a3c8f5 commit 479667478c8504e5facf8d5205e64c2b63ad2da7 Evan Klitzke committed Apr 30, 2008
Showing with 27 additions and 8 deletions.
  1. +27 −8 58/EulerProblem.hs
View
@@ -1,30 +1,49 @@
module Main where
+import Data.Array
import Primes
myOdds :: [Int]
myOdds = [x | x <- [1000..], odd x]
-diagne, diagnw, diagsw, diagse :: [Integer]
+diagne, diagnw, diagsw, diagse :: Integral a => [a]
diagne = [x^2 - x + 1 | x <- [2..], even x]
diagnw = [x^2 + 1 | x <- [2..], even x]
diagsw = [x^2 + x + 1 | x <- [2..], even x]
diagse = [x^2 | x <- [3..], odd x]
-square :: Int -> [Integer]
-square n = concat (map (take n') [diagne, diagnw, diagsw, diagse])
+-- Returns the numbers in the square with a side of length n
+square :: Integral a => Int -> [a]
+square n = 1 : (concat (map (take n') [diagne, diagnw, diagsw, diagse]))
where n' = (n - 1) `div` 2
-squares :: [(Int, [Integer])]
-squares = [(o, square o) | o <- myOdds]
+squareArray :: Integral a => Array Int [a]
+squareArray = array (3,30000) [(n, square n) | n <- [3..30000]]
primesRatio :: Integral a => [a] -> Float
primesRatio xs = (fromIntegral n) / (fromIntegral ln)
where
n = length [x | x <- xs, isPrime x]
ln = length xs
-magic (a, b) = (primesRatio b) > 0.1
-
-answer = fst $ head $ dropWhile magic squares
+magic b = (primesRatio b) < 0.10
+
+halfInt :: Integral a => a -> a -> a
+halfInt a b = (a + b) `div` 2
+
+findAnswer :: Bool -> Int -> Int -> Int
+findAnswer False a b =
+ if magic (squareArray!b)
+ then findAnswer True a b
+ else findAnswer False b (2*b)
+findAnswer True a b
+ | a == b = a
+ | a == (b - 1) = if magic (squareArray!a) then a else b
+ | otherwise = if magic (squareArray!h)
+ then findAnswer True a h
+ else findAnswer True h b
+ where
+ h = halfInt a b
+
+answer = findAnswer False 3 7
main = print answer

0 comments on commit 4796674

Please sign in to comment.