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 Control.Monad ()
import Debug.Trace (trace) import Debug.Trace (trace)
f' :: Integer -> Integer main :: IO ()
f' n = f'' 0 n main = print $ map f [2^100000..]
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"
f :: Integer -> Integer f :: Integer -> Integer
f n = s 0 n f n = s 1 n
where where
s :: Integer -> Integer -> Integer s :: Integer -> Integer -> Integer
s i n s i n
| n == 1 = i | n == 1 = i
| even n = s i' (n `div` 2) | n == 0 = i
| odd n = s i' (3*n + 1) | n == (-1) = i
where i' = i + 1 | n == (-5) = i
| n == (-17) = i
| even n = s (succ i) (n `div` 2)
| odd n = s (succ i) (3*n + 1)
main :: IO () f' :: Integer -> Integer
main = print $ map f [2^361..] 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 -- collatz collect
-- generate the collatz sequence and return it -- generate the collatz sequence and return it
cc :: Integer -> [Integer] cc :: Integer -> [Integer]
cc n = cc' [] n cc n = cc' [] n
where where
cc' :: [Integer] -> Integer -> [Integer] cc' :: [Integer] -> Integer -> [Integer]
cc' acc n 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) | even n = cc' acc' (n `div` 2)
| odd n = cc' acc' (3*n + 1) | odd n = cc' acc' (3*n + 1)
where acc' = acc <> [n] 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]