1
0
Fork 0

Compare commits

...

4 Commits

1 changed files with 35 additions and 27 deletions

62
src/3n+1/Main.hs Executable file → Normal file
View File

@ -1,47 +1,55 @@
{-
The Simplest Math Problem No One Can Solve - Collatz Conjecture
https://youtu.be/094y1Z2wpJg
-}
import Control.Monad ()
import Debug.Trace (trace)
f' :: Integer -> Integer
f' n = f'' 0 n
where
f'' :: Integer -> Integer -> Integer
f'' i n'
| n' == 1 = t' i
| even n' = t $ f'' (i + 1) (n' `div` 2)
| odd n' = t $ f'' (i + 1) (3*n' + 1)
where t = trace ("i: " ++ show i ++ ", number: " ++ show n')
t' = t'' $ trace ("END: " ++ show n ++ ", length: " <> show i) $ t''
t'' = trace "\n#######################################################\n"
main :: IO ()
main = print $ map f [2^100000..]
f :: Integer -> Integer
f n = s 0 n
f n = s 1 n
where
s :: Integer -> Integer -> Integer
s i n
| n == 1 = i
| even n = s i' (n `div` 2)
| odd n = s i' (3*n + 1)
where i' = i + 1
| n == 1 = i
| n == 0 = i
| n == (-1) = i
| n == (-5) = i
| n == (-17) = i
| even n = s (succ i) (n `div` 2)
| odd n = s (succ i) (3*n + 1)
main :: IO ()
main = print $ map f [2^361..]
f' :: Integer -> Integer
f' n = f'' 1 n
where
f'' :: Integer -> Integer -> Integer
f'' i n'
| n' == 1 = t' 0 + t i
| n' == 0 = t' 0 + t i
| n' == (-1 ) = t' 0 + t i
| n' == (-5 ) = t' 0 + t i
| n' == (-17) = t' 0 + t i
| even n' = t $ f'' (succ i) (n' `div` 2)
| odd n' = t $ f'' (succ i) (3*n' + 1)
where t = trace ("i: " ++ show i ++ ", number: " ++ show n')
t' = t'' $ trace ("END: " ++ show n ++ ", length: " <> show i) t''
t'' = trace "\n#######################################################\n"
-- collatz collect
-- generate the collatz sequence and return it
cc :: Integer -> [Integer]
cc n = cc' [] n
where
cc' :: [Integer] -> Integer -> [Integer]
cc' acc n
| n == 1 = 1:acc
| n == 1 = acc <> [1]
| n == 0 = acc <> [0]
| n == (-1) = acc <> [-1]
| n == (-5) = acc <> [-5]
| n == (-17) = acc <> [-17]
| even n = cc' acc' (n `div` 2)
| odd n = cc' acc' (3*n + 1)
where acc' = acc <> [n]
primes :: [Integer]
primes = sieve [2..]
where
sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
isPrime k = (k > 1) && null [ x | x <- [2..k - 1], k `mod` x == 0]