/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 3ms 496.0 KiB
#3 Time Exceeded ≥1100ms ≥564.0 KiB
#4 Time Exceeded ≥1098ms ≥568.0 KiB

Code

#include <iostream>

// This function solves a single test case using an O(sqrt(N)) algorithm.
void solve() {
    // Use long long for N to handle inputs up to 10^9.
    long long n;
    std::cin >> n;

    // We need to calculate sum_{k=2 to N} floor(N/k).
    // This is equal to (sum_{k=1 to N} floor(N/k)) - N.
    // We will calculate the full sum S(N) = sum_{k=1 to N} floor(N/k) first.

    long long total_sum = 0;
    long long i = 1;

    // Loop using the block summation method. The number of iterations is O(sqrt(N)).
    while (i <= n) {
        // For the current i, the value of floor(n/k) is constant.
        long long v = n / i;
        
        // Find the end of the current block. All k from i to last_i
        // will have the same floor(n/k) value, which is v.
        // last_i is the largest integer such that n / last_i >= v.
        // This is equivalent to last_i <= n / v.
        long long last_i = n / v;
        
        // Number of terms in the block [i, last_i].
        long long num_terms = last_i - i + 1;
        
        // Add the contribution of this entire block to the sum.
        total_sum += num_terms * v;
        
        // Move to the beginning of the next block.
        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 is crucial for problems with many test cases.
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);

    int t;
    std::cin >> t;
    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:12:51
Judged At
2025-07-14 18:12:51
Judged By
Score
5
Total Time
≥1100ms
Peak Memory
≥568.0 KiB