Project Euler #135: Same differences

  • + 0 comments

    Here's my C++ solution:

    int main() {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
        unsigned T; scanf("%u", &T);
        
        // x, y, z
        // z, y = z + d, x = z + 2d
        // z^2 + 4dz + 4d^2 - z^2 - 2dz - d^2 - z^2 = n
        // -z^2 + 2dz + 3d^2 = n
        // z^2 - 2dz - 3d^2 + n = 0
        // (z - d)^2 - 4d^2 + n = 0
        // (z - d - 2d)(z - d + 2d) = -n
        // (z - 3d)(z + d) = -n
        // d1*d2 = n
        // z - 3d = -d1
        // z + d = d2
        // 4d = d2 + d1
        // z = d2 - d
        // and d2 >= (d2 + d1)/4
        // 4d2 >= d2 + d1
        // 3d2 > d1
        
        unsigned N = 8e6;
        std::vector<unsigned> sieve(N + 1);
        
        for(unsigned i = 1; i <= N; ++i)
            for(unsigned j = i; j <= N; j += i) {
                if((j/i + i) % 4 == 0 and 3*(j / i) > i)
                    ++sieve[j];
            }
        
        
        for(unsigned i = 0; i < T; ++i) {
            unsigned n; scanf("%u", &n);
            printf("%u\n", sieve[n]);
        }
        
        return 0;