Given 4 integers A, B, C and N, find the value of F(N) such that
F(1) = A + B 
F(2) = B + C 
F(N) = F(N-1) - F(N-2),  for N > 2. 
 
Example 1:
Input: N = 2, A = 2, B = 3, C = 4
Output: 7
Explaination: F(2) = B+C = 3+4 = 7
Example 2:
Input: N = 3, A = 2, B = 3, C = 4
Output: 2
Explaination: F(3) = F(2)- F(1) = 7-5 = 2
Your Task:
You do not need to read input or print anything. Your task is to complete the function modifiedFib() which takes the values N, A, B and C as input parameters and returns F(N). Since F(N) modulo (10^{9}+7).
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^{12}
1 ≤ A, B, C ≤ 10^{9}

Source: geeksforgeeks | Difficulty: EASY
Tags: Number theory

Mathematics

Starter code: #User function Template for python3



class Solution:

    def modifiedFib(self, N, A, B, C):

        # code here

Solutions:
class Solution:

	def modifiedFib(self, N, A, B, C):
		(a, b, c) = (A + B, B + C, C - A)
		n = N % 6
		if n == 1:
			return a % 1000000007
		if n == 2:
			return b % 1000000007
		if n == 3:
			return c % 1000000007
		if n == 4:
			return -a % 1000000007
		if n == 5:
			return -b % 1000000007
		if n == 0:
			return -c % 1000000007


class Solution:

	def modifiedFib(self, N, A, B, C):
		L = [0] * 6
		L[1] = A + B
		L[2] = B + C
		L[3] = C - A
		L[4] = -1 * (A + B)
		L[5] = -1 * (B + C)
		L[0] = -1 * (C - A)
		M = 1000000007
		A = (L[N % 6] % M + 2 * M) % M
		return A


class Solution:

	def modifiedFib(self, N, A, B, C):
		x = A + B
		y = B + C
		N = N % 6
		if N == 0:
			N = 6
		if N == 1:
			return x
		if N == 2:
			return y
		for i in range(N - 2):
			t = y
			y = (y - x) % 1000000007
			x = t
		return y


class Solution:

	def modifiedFib(self, N, A, B, C):
		mod = 1000000007
		if N % 3 == 1:
			if N % 2 == 1:
				return (A + B) % mod
			return -(A + B) % mod
		if N % 3 == 2:
			if N % 2 == 0:
				return (B + C) % mod
			return -(B + C) % mod
		if N % 2 == 1:
			return (C - A) % mod
		return (A - C) % mod


class Solution:

	def modifiedFib(self, N, A, B, C):
		first = A + B
		second = B + C
		if N % 3 == 1:
			if N % 2 == 1:
				return first % (10 ** 9 + 7)
			else:
				return -first % (10 ** 9 + 7)
		elif N % 3 == 2:
			if N % 2 == 0:
				return second % (10 ** 9 + 7)
			else:
				return -second % (10 ** 9 + 7)
		elif N % 3 == 0:
			if N % 2 == 1:
				return (C - A) % (10 ** 9 + 7)
			else:
				return -(C - A) % (10 ** 9 + 7)


class Solution:

	def modifiedFib(self, N, A, B, C):
		x = A + B
		y = B + C
		z = C - A
		if N % 6 == 1:
			return x % (10 ** 9 + 7)
		elif N % 6 == 2:
			return y % (10 ** 9 + 7)
		elif N % 6 == 3:
			return z % (10 ** 9 + 7)
		elif N % 6 == 4:
			return -x % (10 ** 9 + 7)
		elif N % 6 == 5:
			return -y % (10 ** 9 + 7)
		else:
			return -z % (10 ** 9 + 7)