gpt4 book ai didi

c++ - 如何理解这个答案中 "q = i - 4; "的代码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:23 25 4
gpt4 key购买 nike

Problem Description

A number sequence is defined as follows:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).

Input

The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.

Output

For each test case, print the value of f(n) on a single line.

示例输入

1 1 3
1 2 10
0 0 0

示例输出

2
5

代码

#include <iostream>
using namespace std;

int f[54] = {0, 1, 1};
int main()
{
int A, B, n, q = 1;
while (cin >> A >> B >> n && A && B && n)
{
for (int i = 3; i < 54; ++i)
{
f[i] = (A * f[i - 1] + B * f[i - 2]) % 7;
if (i > 4)
{
if (f[i - 1] == f[3] && f[i] == f[4]) //here too
{
q = i - 4; //I can't catch the point
}
}
}
cout << f[n % q] << endl;

}
return 0;
}

最佳答案

鉴于 f(n) 完全由 f(n - 1)f(n - 2) 以及任何 决定code>f(x)是0到6的整数,f(n - 1)f(n - 2)只有7*7=49种组合)。这意味着 f(x) 是周期性的,最大周期为 49。一旦我们知道周期,计算 f(n) 就像 f(n % period) 假设我们已经计算了 f(0)..f(48)。具体周期取决于AB,需要计算。为了计算周期,我们只需要找到 f 的两个连续值的重复。也就是说,如果 f(x) == f(y) && f(x + 1) == f(y + 1),则 |y - x|f 的一个周期或其整数倍。请注意,f(n) == f(n % (k*period))f(n) == f(n % period) 一样有效。因此,在所讨论的代码中,q 要么是 f 的一个周期,要么是它的整数倍。

现在,为什么代码预先计算 f(0)..f(53) 而不是 f(0)..f(48)?我认为这是一种矫枉过正,因为超过最大周期的两个额外元素就足够了。

有关代码的另一个令人不安的事情是 f[0] 是一个假值,如果 nq。这可能是一个错误。为了防止它发生,我会将 f 的索引移动一个,使 f(0) == 1 && f(1) == 1 而不是 f(1) == 1 && f(2) == 1

关于c++ - 如何理解这个答案中 "q = i - 4; "的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44720468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com