in c++
تم الإنشاء في: ٢٠ أبريل ٢٠٢٦
تمت الإجابة باستخدام GPT-5.4 Thinking بواسطة Chat01
تم الإنشاء في: ٢٠ أبريل ٢٠٢٦
تمت الإجابة باستخدام GPT-5.4 Thinking بواسطة Chat01
in c++
Use this C++ solution:
cpp#include <bits/stdc++.h> using namespace std; long long solution(int N) { vector<int> spf(N + 1); // Smallest prime factor sieve for (int i = 0; i <= N; i++) spf[i] = i; for (int i = 2; i * i <= N; i++) { if (spf[i] == i) { for (int j = i * i; j <= N; j += i) { if (spf[j] == j) spf[j] = i; } } } unordered_map<int, long long> freq; // Compute square-free kernel of every number for (int x = 1; x <= N; x++) { int t = x; int kernel = 1; while (t > 1) { int p = spf[t]; int cnt = 0; while (t % p == 0) { t /= p; cnt++; } if (cnt % 2 == 1) kernel *= p; } freq[kernel]++; } long long ans = 0; for (auto &it : freq) { ans += it.second * it.second; } return ans; } int main() { int N; cin >> N; cout << solution(N) << '\n'; return 0; }
How it works:
i * j is a perfect square iff i and j have the same square-free part.12 = 3 * 2^2 → square-free part = 327 = 3 * 3^2 → square-free part = 312 * 27 is a perfect square.1..N share the same square-free part.k, it contributes k * k ordered pairs.For the sample:
N = 3(1,1), (2,2), (3,3)3Time complexity: O(N log log N)
Space complexity: O(N)
If you want, I can also give a more interview-style version with the solution(int N) function only.
sql
sqlSELECT c.name, SUM(oi.quantity * oi.price) AS total_spent FROM customers c JOIN orders o ON c.customer_id = o.customer_id JOIN order_items oi ON o.order_id = oi.order_id GROUP BY c.customer_id, c.name HAVING SUM(oi.quantity * oi.price) > 500 ORDER BY total_spent DESC;
For the sample, this returns:
sqlAlice | 600
Because Alice spent:
1 * 400 = 4002 * 50 = 1001 * 100 = 100Total = 600
If you want, I can also give a PostgreSQL/MSSQL-compatible version, but this one works in MySQL 8.0.