Advertisement
banovski

Triangular number verifier (Haskell)

Nov 13th, 2022 (edited)
2,092
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haskell 1.11 KB | Source Code | 0 0
  1. -- No optimization performed during compilation
  2.  
  3. tnvOne :: Integer -> Bool
  4. tnvOne = aux 0 0
  5.   where
  6.     aux a c n
  7.       | a == n = True
  8.       | a > n = False
  9.       | a < n = aux (a + c) (c + 1) n
  10.  
  11. tnvTwo :: Integer -> Bool
  12. tnvTwo = aux 1
  13.   where
  14.     aux c n
  15.       | n == 0 = True
  16.       | n < 0 = False
  17.       | n > 0 = aux (c + 1) (n - c)
  18.  
  19. tnvThree :: Integer -> Bool
  20. tnvThree = aux 0
  21.   where
  22.     aux c n
  23.       | n > tng c = aux (c + 1) n
  24.       | n == tng c = True
  25.       | n < tng c = False
  26.       where
  27.         tng x = x * (x + 1) `div` 2
  28.  
  29. tnvFour :: (RealFrac t, Floating t) => t -> Bool
  30. tnvFour n = ceiling m == floor m
  31.   where
  32.     m = sqrt (n * 8 + 1)
  33.  
  34. theNumber = 1000000000000
  35.  
  36. main :: IO ()
  37. main = do
  38.   -- print $ tnvOne theNumber
  39.   -- total time = 0.59 secs (589 ticks @ 1000 us, 1 processor)
  40.   -- print $ tnvTwo theNumber
  41.   -- total time = 0.88 secs (883 ticks @ 1000 us, 1 processor)
  42.   -- print $ tnvThree theNumber
  43.   -- total time = 1.28 secs (1283 ticks @ 1000 us, 1 processor)
  44.   -- print $ tnvFour theNumber
  45.   -- total time = 0.00 secs (0 ticks @ 1000 us, 1 processor)
  46.   return ()
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement