[UCSD白板题] The Last Digit of a Large Fibonacci Number

时间:2022-08-29 18:41:14

Problem Introduction

The Fibonacci numbers are defined as follows: \(F_0=0\), \(F_1=1\),and \(F_i=F_{i-1}+F_{i-2}\) for $ i \geq 2$.

Problem Description

Task.Given an integer \(n\),find the last digit of the \(n\)th Fibonacci number \(F_n\)(that is , \(F_n \ mod \ 10\)).

Input Format.The input consists of a single integer \(n\).

Constraints.\(0 \leq n \leq 10^7\).

Output Format.Output the last digit of \(F_n\).

Sample 1.
Input:

3

Output:

2

Sample 2.
Input:

327305

Output:

5

Solution

# Uses python3
import sys

def get_fibonacci_last_digit(n):
    x,y = 0,1
    while n > 0:
        x,y,n = y%10,(x+y)%10,n-1
    return x

if __name__ == '__main__':
    input = sys.stdin.read()
    n = int(input)
    print(get_fibonacci_last_digit(n))