矩阵计算
题目描述
Description
Let’s define a Series Whose recurrence formula is as follows :
C(n)= 3C(i-1) + 4C(i-2) + 5C(i-3) + 6C(i-4)
C(0)= 2
C(1)= 0
C(2)= 1
C(3)= 7
Now based on this Series a Matrix Mi,j of size nn is to be formed.The top left cell is(1,1) and the bottom right corner is (n,n). Each cell (i,j) of the Matrix contains either 1 or 0. If C( (i*j)^3 ) is odd, Mi,j is 1, otherwise, it’s 0.Count the total number of ones in the Matrix.
Input
First Line Of the input will contain an integer ‘T’- the number of test cases . Each of the next ‘T’ lines consists of an integer ‘n’.-denoting the size of the matrix.
Constraints :
1 ≤ T ≤ 1000
1 ≤ n ≤ 1000
Output
For each test case, output a single Integer -the taste value fo the dish of size-n*n.
Sample Input 1
1
2
Sample Output 1
0
题目解析
- 给出了一个递推公式和四个初始值,因此我们可以算出任意的C(n)
- 给定一个方阵,方阵中的每个位置的值为C((i*j)3) ,其中i,j为元素坐标
- 若C((i*j)3)是奇数,则将该位置的值更新为1,如果不是,就更新为0
- 统计矩阵中1的个数,并输出
思路解析
这道题如果按照上述做法,一定是很复杂的,(i*j)3本身就很大了,这种数学问题+递推公式的可能会有一定的规律,简单的尝试一下,不难发现这个数列的奇偶服从一定的规律,每7个一循环
def test():
C_arr = [2, 0, 1, 7]
C_arr = list(map(lambda x: x % 2, C_arr))
print(C_arr)
for i in range(4, 21):
C_temp = (C_arr[i - 1] % 2 + C_arr[i - 3] % 2) % 2
C_arr.append(C_temp)
print(C_arr) # 规律0, 0, 1, 1, 1, 0, 1
然后就简单了,按照公式计算,每7个一循环,统计下1的个数就可以了
注意:
- 要判断奇偶性,因此要有%运算,即C(N)%2,因此会想到关于%运算的性质
首先(a+b)%c = (a%c +b%c)%c因为C(n)= 3C(i-1) + 4C(i-2) + 5C(i-3) + 6C(i-4),求C(n)%2,因为C(n)的第二项和第四项一定是偶数,所以%2一定为0,所以不去考虑,
即C(n)%2 = (3C(i-1)%2+ 5C(i-3)%2)%2,
根据上述公式推导出了7个一循环的规律 - 计算C(n)%2 = C((i * j)3)时,为了防止(i*j)3溢出并简化运算,可以先对其取余,再进行立方运算,见代码实现
代码实现(python)
if __name__ == '__main__':
C_arr = [0, 0, 1, 1, 1, 0, 1]
for _ in range(int(input())):
tar = int(input().strip())
count = 0
for i in range(1, tar + 1):
for j in range(1, tar + 1):
if C_arr[(i % 7 * j % 7) ** 3 % 7] == 1: # 这样求余防止溢出,
count += 1
print(count)