`
tangtong
  • 浏览: 62529 次
  • 来自: ...
社区版块
存档分类
最新评论

Section 1.2

阅读更多

1.9 略

1.10 略

1.11

{- recursive style
f3' n 
    | n<3 = n
    | otherwise = f3(n-1) + 2*f3(n-2) + 3*f3(n-3)
-}    

getBegin n = n-(fromIntegral t)-1
    where t = floor (n-3) ::Integer

f3 n
    | n<3 = n
    | otherwise = f3_iter b (b-1) (b-2) (n-2)
                    where b = getBegin n
                          f3_iter a _ _ 0 = a
                          f3_iter a b c k = f3_iter (a+2*b+3*c) a b (k-1)

 1.12

pascal :: Integer -> Integer -> Integer
pascal n k
    | k==1 = 1
    | n==k = 1
    | k<n  = pascal (n-1) k + (pascal (n-1) (k-1))
    | otherwise = error "Invalid!"

 1.13 略

 1.14 略

 1.15 略

 1.16

-- Iterative version of fast-exp
fast_exp :: (Num a)=> a -> Integer -> a
fast_exp b n = exp_iter b n 1
    where exp_iter _ 0 a = a
          exp_iter b n a = if (even n ) then exp_iter (b*b) (n `div` 2) a
                           else exp_iter b (n-1) (a*b)

 1.17 略

 1.18

fast_mult :: Integer -> Integer -> Integer
fast_mult a b = fast_iter a b 0
    where fast_iter _ 0 s = s
          fast_iter a b s = if (even b) then fast_iter (a*2) (b `div` 2) s
                            else fast_iter a (b-1) (s+a)

 1.19

fast_fib :: Integer -> Integer
fast_fib n = fast_iter 1 0 0 1 n
    where fast_iter _ b _ _ 0 = b
          fast_iter a b p q count = 
            if (even count) then
                fast_iter a b (p*p+q*q) (p*q+q*p+q*q) (count `div` 2)
            else
                fast_iter (b*q+a*q+a*p) (b*p+a*q) p q (count-1)
                
fib :: Integer -> Integer
fib 0 =1
fib 1 =1
fib n = fib (n-1) + fib (n-2)          

  1.20 略

  1.21

smallestDivesor :: Integer -> Integer
smallestDivesor n = divTry 2 n
    where divTry a n
            | a*a > n  = n
            | n `mod` a ==0 = a
            | otherwise = divTry (a+1) n
            
main :: IO ()
main = do mapM_ (putStrLn.show.smallestDivesor) [199,1999,19999]       

 1.22 略

 1.23

smallestDivesor' :: Integer -> Integer
smallestDivesor' n = divTry 2 n
    where divTry a n
            | a*a > n  = n
            | n `mod` a ==0 = a
            | otherwise = divTry (next a) n
          next a = if a==2 then 3 else (a+2)

 1.24~1.28 略 质数问题,以后总结

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics