Guest User

Untitled

a guest
Jul 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. module Kata.CubeFinder where
  2.  
  3.  
  4. -- Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
  5.  
  6. -- You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
  7.  
  8. -- The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.
  9.  
  10. -- Examples:
  11. -- findNb(1071225) --> 45
  12. -- findNb(91716553919377) --> -1
  13.  
  14.  
  15. -- Brute force, didn't work
  16. -- findNb :: Integer -> Integer
  17. -- findNb m = recurse m 0 where
  18. -- recurse 0 n = n - 1
  19. -- recurse m n = if (m < 0)
  20. -- then - 1
  21. -- else recurse (m - (n ^ 3)) (n + 1)
  22. import Debug.Trace
  23.  
  24. findNb :: Integer -> Integer
  25. findNb m = if (isInt n) then round n else -1
  26. where
  27. n = cuadraticFormula (fromInteger 1) (fromInteger 1) c
  28. c = -2 * sqrt (fromInteger m )
  29.  
  30.  
  31. isInt x = x == fromInteger (round x)
  32.  
  33.  
  34. cuadraticFormula :: Double -> Double -> Double -> Double
  35. cuadraticFormula a b c = trace (show a ++ " | " ++ show b ++ " | " ++ show c) ((-b) + sqrt (b ^ 2 - (4 * a * c))) / (2 * a)
Add Comment
Please, Sign In to add comment