yingpotter

[99p]Arith(Complete)

Jul 7th, 2011
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import List
  2.  
  3. -- problem 31  
  4. isPrime ::Integral a => a -> Bool
  5. isPrime 1 = False
  6. isPrime n = foldr (&&) True (map (0 /= ) (map (n `mod`) [2..n-1]))
  7.  
  8. -- problem 32
  9. myGCD :: Integral a => a -> a -> a
  10. myGCD 0 _ = 0
  11. myGCD _ 0 = 0
  12. myGCD m n
  13.       | larger `mod` small == 0  = small
  14.       | otherwise  = myGCD small (larger `mod` small)
  15.       where larger = max m n
  16.             small  = min m n
  17.            
  18. -- problem 33
  19. coprime :: Integral a => a -> a -> Bool
  20. coprime m n = (myGCD m n) ==1
  21.            
  22. -- problem 34
  23. totient :: (Num b, Integral a) => a -> b
  24. totient 0 = 0
  25. totient 1 = 1
  26. totient n = foldr (+) 0 (map f [1..n-1])
  27.           where f x = if coprime x n then 1 else 0
  28.  
  29. -- problem 35
  30. leastPrime :: Integral a => a -> a
  31. leastPrime 1 = 1
  32. leastPrime n = f n [2..n]
  33.                where f n (x:xs) = if (n `mod` x == 0) then x else (f n xs)
  34. primeFactor :: Integral a => a -> [a]
  35. primeFactor 1 = []
  36. primeFactor n = (leastPrime n) : primeFactor (n `div` (leastPrime n))
  37.  
  38. -- problem 36
  39. encode :: Eq t => [t] -> [(t, Int)]
  40. encode [] = []
  41. encode xs = map (\x -> (head x,length x)) (group xs)
  42. prime_factors_mult :: Integer -> [(Integer,Int)]
  43. prime_factors_mult = encode . primeFactor
  44.  
  45. -- problem 37
  46. totientK :: Integer -> Integer
  47. totientK 0 = 0
  48. totientK 1 = 1
  49. totientK n = product [(p - 1) * p ^ (m - 1) | (p, m) <- prime_factors_mult n]
  50.  
  51. -- problem 39
  52. primesR :: Integral t => t -> t -> [t]
  53. primesR a b = [x | x <- [a..b], isPrime(x)]
  54.  
  55. -- problem 40
  56. goldbach :: Integral t => t -> (t,t)
  57. goldbach 0 = error "no answer"
  58. goldbach 2 = error "no answer"
  59. goldbach n
  60.          | n `mod` 2 /=0  = error "not an even nat"
  61.          | n `mod` 2 == 0  = head [(x,y) | x <- [2..(n `div` 2)],  y <- [(n `div` 2)..n], x+y == n, isPrime(x), isPrime(y)]
  62.        
  63. -- problem 41
  64. goldbachList :: Integral t => t -> t -> [(t,t)]
  65. goldbachList a b = [(goldbach x) | x <- [a..b], x>3, x `mod` 2 == 0]
  66. goldbachList' :: Integral t => t -> t -> t -> [(t,t)]
  67. goldbachList' a b k =[(goldbach x) | x <- [a..b], x>3, x `mod` 2 == 0, fst(goldbach x) >= k]
Advertisement
Add Comment
Please, Sign In to add comment