Created
July 22, 2018 09:09
-
-
Save HamsterofDeath/0d289d8e1665c500e9f89b00dbbe4e67 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
def convergentFractions:Iterator[(BigInt, BigInt)] = { | |
val fractions = continuedFractions.memoizedByIndex | |
val forDenominator = (i:Int) => fractions(i+1) | |
val cache = mutable.HashMap.empty[(Int,Boolean), BigInt] | |
def eval(n:Int, isNumerator:Boolean): BigInt = { | |
cache.getOrElseUpdate((n, isNumerator), { | |
val on = if (isNumerator) fractions else forDenominator | |
n match { | |
case larger if larger > 2 => | |
val a = on(larger - 2) | |
val b = eval(larger - 1, isNumerator) | |
val c = eval(larger - 2, isNumerator) | |
a * b + c | |
case 2 => on(0) | |
case 1 => BigInt(1) | |
case _ => throw new IllegalArgumentException(n.toString) | |
} | |
}) | |
} | |
Iterator.from(1).map { n => | |
val num = eval(n + 1, isNumerator = true) | |
val denom = eval(n, isNumerator = false) | |
(num, denom) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment