Jacobi symbol: Difference between revisions
m
→{{header|Haskell}}
No edit summary |
|||
Line 644:
Or, expressing it slightly differently, and adding a tabulation:
<lang haskell>import Data.
import Data.List (replicate, transpose)
import Data.List.Split (chunksOf)
jacobi :: Int -> Int -> Int
Line 654 ⟶ 656:
go 0 _ = 0
go x y
| even r =
plusMinus
(rem y 8 `elem` [3, 5])
(go (div r 2) y)
| otherwise = plusMinus (p r && p y) (go y r)
where
Line 661 ⟶ 666:
r = rem x y
▲------------------------- DISPLAY -------------------------
jacobiTable :: Int -> Int -> String▼
jacobiTable nCols nRows =▼
let rowLabels = [1,3 .. (2 * nRows)]▼
colLabels = [0 .. pred nCols]▼
in withColumnLabels ("" : fmap show colLabels) $▼
labelledRows (fmap show rowLabels) $▼
paddedCols $▼
chunksOf nRows $▼
uncurry jacobi <$> ((,) <$> colLabels <*> rowLabels)▼
--------------------------- TEST
main :: IO ()
main = putStrLn $ jacobiTable 11 9
-------------------------
▲jacobiTable :: Int -> Int -> String
paddedCols▼
▲jacobiTable nCols nRows =
:: Show a▼
▲ let rowLabels = [1, 3 .. (2 * nRows)]
=> [[a]] -> [[String]]▼
▲ colLabels = [0 .. pred nCols]
▲ in withColumnLabels ("" : fmap show colLabels) $
▲ labelledRows (fmap show rowLabels) $
▲ paddedCols $
▲ chunksOf nRows $
uncurry jacobi
------------------- TABULATION FUNCTIONS -----------------
▲paddedCols ::
[[a]] ->
paddedCols cols =
let scols = fmap show <$> cols
w = maximum $ length <$> concat scols
in map (justifyRight w ' ') <$> scols
labelledRows :: [String] -> [[String]] -> [[String]]
labelledRows labels cols =
let w = maximum $ map length labels
in zipWith
in zipWith (:) ((++ " ->") . justifyRight w ' ' <$> labels) (transpose cols)▼
(:)
(transpose cols)
withColumnLabels :: [String] -> [[String]] -> String
withColumnLabels
withColumnLabels labels rows@(x : _) =
let labelRow =
in unlines $ labelRow : replicate (length labelRow) '-' : fmap unwords rows▼
unwords $
zipWith
(`justifyRight` ' ')
(length <$> x)
labels
in unlines $
labelRow :
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c = (drop . length) <*> (replicate n c
{{Out}}
<pre> 0 1 2 3 4 5 6 7 8 9 10
|