Program to find out the scalar products of vectors generated from an infinite sequence in Python



Suppose we are given three integer numbers c, m, and n. We have to generate an infinite sequence, where the first value is 0, the second value is c, and from the third value onwards it is equal to ki = (ki-2 + ki-1) mod m. We have to generate all the values in the series up to item k2n+1. Now from the values of the series; we take two consecutive values in the sequence as the x and y coordinates of a two-dimensional vector and generate n number of vectors. Point to be noted, we use the values in the sequence from the third value. There is another set S where each value is the scalar product of vector i and vector j where 1 <= i, j <= n and i != j. We have to find out the number of different residues in the set S. If the value is very large, we mod it by m.

So, if the input is like 5, 6, 4, then the output will be 3

The sequence generated is: [0, 5, 5, 4, 3, 1, 4, 5, 3, 2].

The vectors are: (5, 4), (3, 1), (4, 5), (3, 2).

From the scalar product of the vectors, there are only three residue values mod 6 in the set S.

The result is thus 3 mod 6 = 3.

To solve this, we will follow these steps −

  • if n is same as 1, then
    • return 0
  • otherwise,
    • temp_arr:= a new list of size 2*n+2 initialized with 0s
    • temp_arr[0] := 0
    • temp_arr[1] := c
    • arr2 := a new list
    • for i in range 2 to 2 * n+2, do
      • temp_arr[i] :=(temp_arr[i - 1] + temp_arr[i - 2]) mod m
    • for i in range 2 to 2 * n-2, increase by 2, do
      • temp :=(temp_arr[i] * temp_arr[i + 2] + temp_arr[i + 1] * temp_arr[i + 3]) mod m
      • insert temp at the end of arr2
      • temp :=(temp_arr[i] * temp_arr[i+4] + temp_arr[i+1] * temp_arr[i+5]) mod m
      • insert temp at the end of arr2
    • temp :=(temp_arr[2 * n-2] * temp_arr[2 * n] + temp_arr[2 * n-1] * temp_arr[2 * n+1]) mod m
    • insert temp at the end of arr2
    • remove duplicate items from arr2
    • return size of arr2

Example

Let us see the following implementation to get better understanding −

def solve(c, m, n):
   if (n == 1):
      return 0
   else:
      temp_arr=[0 for i in range(2 * n+2)]
      temp_arr[0] = 0
      temp_arr[1] = c
      arr2 = []
      for i in range(2, 2 * n+2):
         temp_arr[i] = (temp_arr[i - 1] + temp_arr[i - 2]) % m
      for i in range(2, 2 * n-2, 2):
         temp = (temp_arr[i] * temp_arr[i + 2] + temp_arr[i + 1] * temp_arr[i + 3]) % m
         arr2.append(temp)
         temp = (temp_arr[i] * temp_arr[i+4] + temp_arr[i+1] * temp_arr[i+5]) % m
         arr2.append(temp)
      temp = (temp_arr[2 * n-2] * temp_arr[2 * n] + temp_arr[2 * n- 1] * temp_arr[2 * n+1]) % m
      arr2.append(temp)
      arr2 = set(arr2)
      return len(arr2)

print(solve(5, 6, 4))

Input

5, 6, 4

Output

3

Advertisements