public
Last active

Stack overflow when constructing a vector, an easier solution.

  • Download Gist
SO.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
-- See http://stackoverflow.com/questions/15991634/why-i-take-a-message-for-stack-overflow-in-haskell/15992529#15992529
import Control.DeepSeq (($!!))
import Data.Vector as V hiding ((++))
import System.Environment
 
d :: Vector Integer
d = generate 1000000
(\z -> case z of
0 -> 2
1 -> 3
2 -> 5
_ -> if odd z then (d ! (z-1)) +2 else (d ! (z-1)) + 4)
 
 
algorithmA :: Integer -> Int -> Integer -> [Integer] -> [Integer]
algorithmA _ _ 1 pt = pt
algorithmA t k n pt =
let dk = d ! k
q = div n dk
r = mod n dk
in if r /=0 then
if q>dk then
algorithmA t (k+1) n pt
else (n:pt)
else
algorithmA (t+1) k q (dk:pt)
 
main :: IO ()
main = do
args <- getArgs
let n = read (args !! 0)
let l = V.last $!! d
if (floor(sqrt(fromIntegral n))) > l
then error ("The square root of number is greater than "
++ show l)
else
print (algorithmA 0 0 n [])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.