Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Uses python3
- import sys
- def fibonacci_partial_sum_naive(m, n):
- result_sum = 0
- current_number = 0
- next_number = 1
- for i in range(n + 1):
- if i >= m:
- result_sum += current_number
- current_number, next_number = next_number, current_number + next_number
- return result_sum % 10
- def get_fibonacci_huge_naive(n, m):
- if n <= 1:
- return n
- previous = 0
- current = 1
- for _ in range(n - 1):
- previous, current = current, previous + current
- return current % m
- # property of the Fibonacci remainders of modulo n operation is that you can find the next remainder by adding
- # the last 2 and looped on n ie. for F(13) mod 5 , r(13) = r(11) + r(12) = 4 + 4 = 3 because 8 = 5 + 3
- # also the pattern of remainders repeat every time you encounter the a 0 followed by a 1. That is the mark for the
- # length of the Pisano period.
- def get_fibonacci_huge_faster(p, q):
- if p <= 1:
- return p
- previous = 1
- current = 1
- pisano_period = 1
- while (previous, current) != (0, 1):
- # we loop back on q to get the remainder of the remainders sum
- previous, current = current, (previous + current) % q
- pisano_period += 1
- # we just need to find the remainder of p when divided by the Pisano period.
- # numbers are small enough now to use the naive approach
- return get_fibonacci_huge_naive(p % pisano_period, q)
- # turns out that Sum(F(0->i)) = F(i+2) % 10 - 1
- def fib_sum_last_digit_faster(p):
- res = get_fibonacci_huge_faster(p + 2, 10) - 1
- # we loop back on 10 that is if the last digit is 0 we have reached a multiple of 10 and there for the last
- # number is 9
- if res == -1:
- res = 9
- return res
- # partial_sum(F(from), F(to)) = sum(F(to)) - sum(F(from - 1))
- def fibonacci_partial_sum_faster(p, q):
- if p == q:
- return get_fibonacci_huge_faster(p, 10)
- elif p == 0:
- return fib_sum_last_digit_faster(q)
- res = fib_sum_last_digit_faster(q) - fib_sum_last_digit_faster(p - 1)
- # again we loop back on 10 if last digit of sum(F(p)) exceeds sum(F(q))
- return res if res >= 0 else 10 + res
- if __name__ == '__main__':
- user_input = sys.stdin.read()
- from_, to = map(int, user_input.split())
- print(fibonacci_partial_sum_faster(from_, to))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement