## SPOJ 515. Collatz

SPOJ 515. Collatz is bit archaic in expression. Its 3 * n + 1 problem . and if K>1. If is odd then given expression and if is even then . Accepted Haskell code.

import Data.List import Data.Maybe import qualified Data.ByteString.Lazy.Char8 as BS {-- collatz :: Integer -> Integer collatz n = head . filter (\t -> helpCollatz t == 1 ) $ [ 1.. ] where helpCollatz 1 = n helpCollatz k = l where t = helpCollatz ( k - 1 ) l = if odd t then 3 * t + 1 else div t 2 --} solve :: Integer -> Integer solve n = succ . fromIntegral . fromJust . findIndex ( \t -> t == 1 ) . scanl ( \ x y -> if odd x then 3 * x + 1 else div x 2 ) n $ [ 2..] readInt :: BS.ByteString -> Integer readInt = fst . fromJust . BS.readInteger main = BS.interact $ BS.unlines. map ( BS.pack.show . solve . readInt ) . BS.lines

Advertisements

## 3 Comments »

### Leave a Reply

Advertisements

Remarkably well written piece

Comment by Scene | October 17, 2011 |

please help me to write this code in c++…..

my problem is to handle the large input given in test cases

Comment by Prashant Gupta | January 4, 2012 |

@Prashant For c++ you will have to write your own big integer library. Store the numbers in char array or string and implement division by 2 and multiplication 3. Also with some efforts , you can try this problem in python which has inbuilt support for big numbers and simple enough to learn with elegant syntax.

Comment by tiwari_mukesh | January 4, 2012 |