P4143PyramidSequences

xiaruize發表於2024-04-08

數學

等價於在一個 \(n\times m\) 的矩形中做彈球,問經過的整點個數

\(t=gcd(n,m)\) ,將 \(n,m\) 分別除掉 \(t\) ,得到 \(n',m'\)

此時會有 \(n'm'\) 條線段,每條線段經過 \(t\) 個整點,另外還有 \(\lceil \frac{(n'+1)(m'+1)}{2} \rceil\) 個交點

所以最終答案為

\[\lceil \frac{(n'+1)(m'+1)}{2} \rceil+(t-1)n'm' \]

const int INF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1000000007;
const int N = 2e5 + 10;

int n, m;

int gcd(int x, int y)
{
    if (!x)
        return y;
    return gcd(y % x, x);
}

void solve()
{
    cin >> n >> m;
    n--;
    m--;
    int t = gcd(n, m);
    n /= t;
    m /= t;
    cout << ((n + 1) * (m + 1) + 1) / 2 + (t - 1) * n * m << endl;
}

#ifndef ONLINE_JUDGE
bool end_of_memory_use;
#endif

signed main()
{
    // freopen(".in","r",stdin);
    // freopen(".out","w",stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int testcase = 1;
    // cin >> testcase;
    while (testcase--)
        solve();
#ifndef ONLINE_JUDGE
    cerr << "Memory use:" << (&end_of_memory_use - &start_of_memory_use) / 1024.0 / 1024.0 << "MiB" << endl;
    cerr << "Time use:" << (double)clock() / CLOCKS_PER_SEC * 1000.0 << "ms" << endl;
#endif
    return 0;
}