Task 2 of 5

Every Body Pulls on Every Body

Real gravity has no star at the center — every body pulls on every other. For 64 bodies that's 64 × 63 interactions; for a million, half a trillion. On the GPU the shape is beautiful: the outer loop over bodies becomes 64 parallel threads, and each thread keeps a small inner loop over the other 63. O(n²) work, O(n) time per thread, all at once.

One wrinkle: pulls are vectors now, not strengths. The unit direction from you to body j is (dx / r, dy / r), and the strength is mass[j] / r² — multiply them and the x-component of each contribution is mass[j] · dx / r³. This kernel sums just the x-components; skip yourself, or you'll divide by zero.

sixty-three pulls per body, summed in one thread — n² work, n time
Goal: complete the inner loop so each thread returns the net x-acceleration on its body: the sum of mass[j] · dx / r³ over every other body.

Requirements

Hint 1 — where does r³ come from?

Direction dx / r times strength 1 / r² is dx / r³. With r2 = dx*dx + dy*dy in hand, that's r2 * Math.sqrt(r2) — one square root per pair.

Hint 2 — the loop body
const dx = posX[j] - myX;
const dy = posY[j] - myY;
const r2 = dx * dx + dy * dy;
ax += mass[j] * dx / (r2 * Math.sqrt(r2));

Same idea elsewhere

This loop-inside-a-thread is the canonical O(n²) GPU pattern. Fast CUDA and ROCm n-body codes keep exactly this loop but tile it: a thread block stages a chunk of bodies in shared memory so all threads reuse the loads — WebGPU's var<workgroup> and Metal's threadgroup memory exist for the same trick.

All tasks in N-Body Gravity

  1. The Pull of One Star
  2. Every Body Pulls on Every Body
  3. Softening the Singularity
  4. One Tick of the Clock
  5. Put It Together: 128 Bodies

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.