Tvor0zhok

Факториалы Haskell

Feb 27th, 2021 (edited)
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. -- Задача №1
  2. factorial1 :: Int -> Int
  3. factorial1 x = if x == 0 then 1 else x * factorial1 (x - 1)
  4.  
  5. -- Задача №2
  6. factorial2 :: Int -> Int
  7. factorial2 0 = 1
  8. factorial2 x = x * factorial2 (x - 1)
  9.  
  10. -- Задача №3
  11. doubleFact :: Int -> Int
  12. doubleFact x = if x <= 2 then max 1 x else x * doubleFact (x - 2)
  13.  
  14. -- Задача №4
  15. factorial4 :: Int -> Int
  16. factorial4 0 = 1
  17. factorial4 x = if x < 0 then error "arg must be >=0" else x * factorial4 (x - 1)
  18.  
  19. -- Задача №5
  20.  
  21. --1-ый способ:
  22. factorial51 :: Int -> Int
  23. factorial51 x
  24. | x >= 0 = if x == 0 then 1 else x * factorial51 (x - 1)
  25. | otherwise = error "arg must be >=0"
  26.  
  27. --2-ой способ:
  28. factorial52 :: Int -> Int
  29. factorial52 x
  30. | x > 0 = x * factorial52 (x - 1)
  31. | x == 0 = 1
  32. | otherwise = error "arg must be >=0"
  33.  
  34. -- Задача №6
  35.  
  36. --1-ый способ:
  37. factorial61 :: Int -> Int
  38. factorial61 x
  39. | x > 0 = doubleFact x * doubleFact (x - 1)
  40. | x == 0 = 1
  41. | otherwise = error "arg must be >=0"
  42.  
  43. --2-ой способ:
  44. factorial62 :: Int -> Int
  45. factorial62 x | x >= 0 = helper 1 x
  46. | otherwise = error "arg must be >=0"
  47.  
  48. helper :: Int -> Int -> Int
  49. helper acc 0 = acc
  50. helper acc x = helper (acc * x) (x - 1)
  51.  
  52. --3-ий способ:
  53. factorial63 :: Int -> Int
  54. factorial63 n = aux n 1
  55. where
  56. aux n acc
  57. | n <= 1 = acc
  58. | otherwise = aux (n - 1) (n * acc)
Add Comment
Please, Sign In to add comment