Question

e8571c4f-5004-4ca5-a356-60ff5fcf47ad.jpg
fde8378a-0f84-4552-875d-78f4947a742e.jpg
82c61f8f-8a69-42d1-8425-a3be8a5dc4c1.jpg
fbd01396-75a5-4926-8dca-34286f0eea26.jpg

in c++

Réflexion

Clarifying problem details for coding task

The problem involves finding ordered pairs (i, j) where both i and j vary from 1 to N, and i * j is a perfect square. To solve efficiently for N up to 1e5, we need to count such pairs using a mathematical approach based on squarefree components. Let's refine the approach for better performance.

Thought for 16s

Réponse

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.
  • Example:
    • 12 = 3 * 2^2 → square-free part = 3
    • 27 = 3 * 3^2 → square-free part = 3
    • so 12 * 27 is a perfect square.
  • Count how many numbers from 1..N share the same square-free part.
  • If a group has size k, it contributes k * k ordered pairs.

For the sample:

  • N = 3
  • valid pairs: (1,1), (2,2), (3,3)
  • answer = 3

Time 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.

Question

942c5a9b-3e5e-4b3d-a2c6-3f062a5b2ec5.jpg
8de911c1-f10a-40ef-8d21-96c4bfd659ed.jpg
3bb041a8-b699-41e0-8204-eb70b0edd06e.jpg
95be1407-12f2-41a7-8dee-6322f442628f.jpg
17e562d2-bd22-44ed-afd3-9074905506c3.jpg

sql

Réflexion

Thought for a couple of seconds

Réponse

sql
SELECT 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:

sql
Alice | 600

Because Alice spent:

  • Laptop: 1 * 400 = 400
  • Mouse: 2 * 50 = 100
  • Keyboard: 1 * 100 = 100

Total = 600

If you want, I can also give a PostgreSQL/MSSQL-compatible version, but this one works in MySQL 8.0.

Partager cette Q&R