{-# LANGUAGE BangPatterns #-} import Control.Monad import Data.IORef import qualified Data.Vector.Fusion.Stream.Monadic as VFSM stream :: Monad m => Int -> Int -> VFSM.Stream m Int stream !l !r = VFSM.Stream step l where step x | x < r = return $ VFSM.Yield x (x + 1) | otherwise = return $ VFSM.Done {-# INLINE [0] step #-} {-# INLINE [1] stream #-} r09 :: Monad m => (Int -> m ()) -> m () r09 = flip VFSM.mapM_ (stream 0 10) {-# INLINE r09 #-} r19 :: Monad m => (Int -> m ()) -> m () r19 = flip VFSM.mapM_ (stream 1 10) {-# INLINE r19 #-} r03 :: Monad m => (Int -> m ()) -> m () r03 = flip VFSM.mapM_ (stream 0 4) {-# INLINE r03#-} main :: IO () main = do n <- readLn :: IO Int ans <- newIORef (0 :: Int) tmp <- newIORef (0 :: Int) r19 $ \i -> r09 $ \j -> do writeIORef tmp (i * 10 + j) temp <- readIORef tmp when (temp <= n && temp `mod` 3 == 0) $ modifyIORef' ans succ r03 $ \i0 -> r03 $ \i1 -> r03 $ \i2 -> r03 $ \i3 -> r03 $ \i4 -> r03 $ \i5 -> r03 $ \i6 -> r03 $ \i7 -> r03 $ \i8 -> do writeIORef tmp (i0 + i1 * 10 + i2 * 100 + i3 * 1000 + i4 * 10000 + i5 * 100000 + i6 * 1000000 + i7 * 10000000 + i8 * 100000000) modifyIORef' tmp (*3) temp <- readIORef tmp when (temp <= n && temp > 100) $ modifyIORef' ans succ print =<< readIORef ans