From d498fd3ea3e1df8c647b83e5e4922e6af971960b Mon Sep 17 00:00:00 2001 From: Abigail Date: Tue, 11 May 2021 19:29:08 +0200 Subject: Use closed form to calculate Fibonacci numbers for week 112, part 2. --- challenge-112/abigail/python/ch-2.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) (limited to 'challenge-112/abigail/python') diff --git a/challenge-112/abigail/python/ch-2.py b/challenge-112/abigail/python/ch-2.py index 3e2a55750d..da542b06f2 100644 --- a/challenge-112/abigail/python/ch-2.py +++ b/challenge-112/abigail/python/ch-2.py @@ -5,17 +5,14 @@ # # -# Run as: python ch-1.py < input-file +# Run as: python ch-2.py < input-file # import fileinput +from math import sqrt -cache = {0: 1, 1: 1} - -def fib (n): - if not n in cache: - cache [n] = fib (n - 1) + fib (n - 2) - return (cache [n]) +SQRT5 = sqrt (5) +PHI = (1 + SQRT5) / 2 for line in fileinput . input (): - print (fib (int (line))) + print (round (pow (PHI, int (line) + 1) / SQRT5)) -- cgit