/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 3ms 532.0 KiB
#3 Time Exceeded ≥1099ms ≥560.0 KiB
#4 Time Exceeded ≥1100ms ≥568.0 KiB

Code

#include <iostream>

// This function solves a single test case.
void solve() {
    // Read the input N. Use long long as N can be up to 10^9.
    long long n;
    std::cin >> n;

    // We need to find the number of pairs (i, j) such that 1 <= i <= j <= N
    // and gcd(i, j) = |i - j|.
    // As derived, this is equivalent to counting pairs (k, d) where k >= 1, d >= 1
    // and (k + 1) * d <= N.
    // This count is equal to S(N) - N, where S(N) = sum_{i=1 to N} floor(N/i).

    // We calculate S(N) efficiently using the block summation method in O(sqrt(N)).
    long long total_sum = 0;
    long long i = 1;

    while (i <= n) {
        // For the current i, calculate the value v = floor(n / i).
        long long v = n / i;
        
        // Find the largest index 'last_i' for which floor(n / k) is also v.
        // This is given by last_i = floor(n / v).
        long long last_i = n / v;
        
        // The value floor(n/k) is constant (equal to v) for all k from i to last_i.
        // The number of such terms is (last_i - i + 1).
        long long count = last_i - i + 1;
        
        // Add their contribution to the total sum.
        total_sum += count * v;
        
        // Move to the next block. The next i will be last_i + 1.
        i = last_i + 1;
    }

    // The final answer is S(n) - n.
    long long result = total_sum - n;
    std::cout << result << "\n";
}

int main() {
    // Fast I/O in C++.
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);

    // Read the number of test cases.
    int t;
    std::cin >> t;
    // Process each test case.
    while (t--) {
        solve();
    }

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1207 D2. GCD equal Absolute Value (Hard Version)
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-14 18:09:14
Judged At
2025-07-14 18:09:14
Judged By
Score
5
Total Time
≥1100ms
Peak Memory
≥568.0 KiB