summaryrefslogtreecommitdiff
path: root/AlgoDesignAndTechniqueEdxJava/sources/LastDigitOfFibSumAgain.java
blob: 024e94855ec2a972c6d0cef3edae0aeb15c649cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Scanner;

public class LastDigitOfFibSumAgain {

	final static int FIB_PISANO_PERIOD_FOR_TEN = 60;

	public static int getFibNModM(long n) {
		long r = n % FIB_PISANO_PERIOD_FOR_TEN;
		if (r == 0)
			return 0;
		int firstN = 0;
		int secondN = 1;
		int tempHolder = 1;
		for (int i = 1; i < r; i++) {
			tempHolder = (firstN + secondN) % 10;
			firstN = secondN;
			secondN = tempHolder;
		}
		return secondN;
	}

	public static int getLastDigit(long n) {
		if (n <= 1)
			return (int) n;
		int result = getFibNModM(n + 2);
		if (result == 0)
			return 9;
		else
			return result - 1;
	}

	public static void main(String args[]) {
		Scanner in = new Scanner(System.in);
		long m = in.nextLong();
		long n = in.nextLong();

		System.out.println(getLastDigit(m, n));
	}

	public static int getLastDigit(long m, long n) {
		if (m == n)
			return getFibNModM(n);
		else {
			int sumFn = getLastDigit(n);
			int sumFm;
			if (m <= 1)
				sumFm = 0;
			else
				sumFm = getLastDigit(m - 1);
			if (sumFn >= sumFm)
				return sumFn - sumFm;
			else
				return sumFn - sumFm + 10;
		}
	}

}