Last active
December 17, 2015 18:59
-
-
Save paulcc/5656838 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- using Haskell's library for rational numbers, which stores a rational as | |
-- a pair of integer numbers (not limited to 32 or 64 bits); hence able to do | |
-- exact arithmetic etc up to high numbers | |
import Data.Ratio | |
-- the core function: spits out a list of ascending n for the fractions | |
-- works by reducing (a/b) to 1/ceil(b/a) + ... | |
fractionize t | |
| t == 0 = [] | |
| diff >= 0 = next : fractionize diff | |
where | |
diff = t - 1 % next | |
next = ceiling (1 / t) | |
-- examples | |
-- fractionize (6 % 7) =====> [2,3,42] | |
-- fractionize (10242 % 1414244) =====> [139,20927,494331640,341895644508855255,2674143744440687043922347253562499240] | |
--- check: sum (map (1/) [139,20927,494331640,341895644508855255,2674143744440687043922347253562499240]) - 10242 / 1414244 (gives 0) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- add this code to the above, and run "main" to run | |
-- various tests | |
-- some testing/demonstration functions | |
-- running over a n * m grid, where i < j | |
chk f n m | |
= [ let ns = f (i%j) in (i,j, ns, sum (map (1%) ns) == i%j) | |
| i <- [1 .. n], j <- [1..m], i < j ] | |
-- nice formatting etc | |
tst f n | |
= putStrLn | |
$ case [ show (i,j,ns) | (i,j,ns,False) <- chk f n n ] of | |
[] -> "No problems" | |
fs -> unlines $ "FOUND BAD:" : fs | |
-- run for numbers up to 200 | |
main = tst (fractionize) 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment