Commits

WANG Yanjin  committed 1c74fff

optimize p36, solve p37

  • Participants
  • Parent commits 0cb5d8c

Comments (0)

Files changed (2)

 import System.Environment (getArgs)
 import System.CPUTime (getCPUTime)
 
-import Data.List (iterate, concat, all, maximum, nub, group, subsequences, maximumBy, elemIndex, tails, transpose, sort, null)
-import Data.Char (digitToInt, ord)
+import Data.List (iterate, concat, all, maximum, nub, group, subsequences, maximumBy, elemIndex, tails, transpose, sort, null, inits)
+import Data.Char (digitToInt, ord, intToDigit)
 import Data.Bits (testBit, shiftR)
 
 import Data.Time.Calendar (Day, addDays, fromGregorian, diffDays, toGregorian)
 
 import Control.Applicative ((<*>), (<$>))
 
+import qualified Numeric as Num
+
 import Debug.Trace (trace)
 
 
         isCircular n | any (\c -> elem c "024568") (show n) = False
                      | otherwise = all (\p -> elem p p1m) (circulars n)
 
-p36 = sum [x | x <- [1..999999], isPalind x && isPalind2 x]
+p36 = sum [x | x <- [1..999999], isPal (siab 10 x) && isPal (siab 2 x)]
     where
-        getrBits :: Int -> [Int]
-        getrBits 0 = [0]
-        getrBits 1 = [1]
-        getrBits n = (mod n 2):(getrBits (div n 2))
-        isPalind n = (reverse $ show n) == show n
-        isPalind2 n = (reverse $ getrBits n) == getrBits n
+        isPal s = s == reverse s
+        siab base x = Num.showIntAtBase base intToDigit x ""
+
+p37 = sum $ take 11 [x | x <- (dropWhile (<10) primesSA), preCheck x && isPrimeR x && isPrimeL x]
+    where
+        preCheck n = all (\c -> not $ elem c "0468") (show n) && all (\c-> not $ elem c "25") (tail . init . show $ n) 
+        isPrimeR n = all isPrime (map (\y -> read y :: Int) (init $ tails (show n)))
+        isPrimeL n = all isPrime (map (\y -> read y :: Int) (tail $ inits (show n)))
+
 -- solutions end
 
 
 
     args <- getArgs
     let n = read (args !! 0) :: Int
-        xxx = p36
+        xxx = p37
     print $ xxx
 
     t2 <- getCPUTime
     print('Sum: ', _sum)
 
 if __name__ == '__main__':
-	print(p35())
+	print(p37())
 	print("Seconds:", time.clock() - start)