summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHaidong Ji2018-08-29 16:24:08 -0500
committerHaidong Ji2018-08-29 16:24:08 -0500
commita6fbcd67ecf83f4715a7fff4ae52cdf91687c8d6 (patch)
tree5f2e3e482499429c5fe2e3754d71d944bf001e77
parentb4c46291059c52396aa4edb6cf96e66d10b17ccd (diff)
Last digit of partial fib sums done
It was pretty easy, just reimplemting the algorithm I've finished with Java.
-rw-r--r--AlgoDesignAndTechniqueEdxPython/sources/lastdigitoffibsumagain.py52
-rw-r--r--AlgoDesignAndTechniqueEdxPython/tests/lastdigitoffibsumagainTest.py25
2 files changed, 77 insertions, 0 deletions
diff --git a/AlgoDesignAndTechniqueEdxPython/sources/lastdigitoffibsumagain.py b/AlgoDesignAndTechniqueEdxPython/sources/lastdigitoffibsumagain.py
new file mode 100644
index 0000000..21de833
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxPython/sources/lastdigitoffibsumagain.py
@@ -0,0 +1,52 @@
+# Uses python3
+import sys
+
+FIB_PISANO_PERIOD_FOR_TEN = 60;
+
+def getFibNModM(n):
+ r = n % FIB_PISANO_PERIOD_FOR_TEN
+ if r==0:
+ return 0
+ firstN = 0
+ secondN = 1
+ tempHolder = 1
+
+ for _ in range(2, r + 1):
+ tempHolder = (firstN + secondN) % 10;
+ firstN = secondN
+ secondN = tempHolder
+# return getFibOptimized(n % p) % m
+ return secondN
+
+
+def getLastDigit(n):
+ if n<=1:
+ return n
+ result = getFibNModM(n+2)
+ if result==0:
+ return 9
+ else:
+ return result -1
+
+def getPartialSumLastDigit(m, n):
+ if m==n:
+ return getFibNModM(n)
+ else:
+ sumFn=getLastDigit(n)
+ if m<=1:
+ sumFm = 0
+ else:
+ sumFm = getLastDigit(m-1)
+ if sumFn>=sumFm:
+ return sumFn-sumFm
+ else:
+ return sumFn - sumFm + 10
+
+if __name__ == '__main__':
+ input = sys.stdin.read()
+ tokens = input.split()
+ m = int(tokens[0])
+ n = int(tokens[1])
+ print(getPartialSumLastDigit(m, n))
+
+
diff --git a/AlgoDesignAndTechniqueEdxPython/tests/lastdigitoffibsumagainTest.py b/AlgoDesignAndTechniqueEdxPython/tests/lastdigitoffibsumagainTest.py
new file mode 100644
index 0000000..48af95f
--- /dev/null
+++ b/AlgoDesignAndTechniqueEdxPython/tests/lastdigitoffibsumagainTest.py
@@ -0,0 +1,25 @@
+'''
+Created on Aug 29, 2018
+
+@author: haidong
+'''
+import unittest
+
+from sources.lastdigitoffibsumagain import getPartialSumLastDigit
+
+class Test(unittest.TestCase):
+
+
+ def testName(self):
+ self.assertEqual(5, getPartialSumLastDigit(5,5))
+ self.assertEqual(1, getPartialSumLastDigit(3,7))
+ self.assertEqual(2, getPartialSumLastDigit(10,200))
+ self.assertEqual(6, getPartialSumLastDigit(5,7))
+ self.assertEqual(7, getPartialSumLastDigit(5,8))
+ self.assertEqual(1, getPartialSumLastDigit(5,9))
+ self.assertEqual(2, getPartialSumLastDigit(1,2))
+
+
+if __name__ == "__main__":
+ #import sys;sys.argv = ['', 'Test.testName']
+ unittest.main() \ No newline at end of file