素数の二進数表記
30分プログラム、その569。前回は二進数表記までしかやらなかったが、今回は素数を二進数表記するところまでやってみる。
素数を計算するのが面倒で二進数表記への変換だけでお茶を濁していたら、GaucheやらAwkで素数計算までやられてしまった。
このままだと負けた気分がするので、素数計算までやってみる。それ以外は前回のと変っていない。
使い方
*Main> main + ++ + + +++ + + + ++ ++ + ++++ + + + ++ + + + ...
ソースコード
import Data.Bits newtype Binary = Binary [Bool] -- toBinary toBinary :: Int -> Binary toBinary n = Binary $ iter [] n where iter xs 0 = False:xs iter xs 1 = True:xs iter xs n = iter (testBit n 0 : xs) $ n `shiftR` 1 fixWidth :: Int -> Binary -> Binary fixWidth n (Binary xs) = Binary $ replicate (n - length xs) False ++ xs instance Show Binary where show (Binary xs) = map (\b -> if b then '+' else ' ') xs -- primes sieve (x:xs) = x:[y | y <- xs, y `mod` x /= 0] primes = sieve [2..] -- main main = mapM_ print $ map (fixWidth 8.toBinary) $ takeWhile (< 256) primes