簡體   English   中英

這個 n 體問題是 O(n^2) 還是 O(n log n)?

[英]Is this n-body problem O(n^2) or O(n log n)?

我正在寫一篇關於 n 體問題的文章,我希望在技術上准確。

代碼在這里 以下是評論和循環:

/**
 * Given N bodies with mass, in a 3d space, calculate the forces of gravity to be applied to each body.  
 * 
 * This function is exported to JavaScript, so only takes/returns numbers and arrays.
 * For N bodies, pass and array of 4N values (x,y,z,mass) and expect a 3N array of forces (x,y,z)
 * Those forcess can be applied to the bodies mass to update the its position in the simulation.
 * Calculate the 3-vector each unique pair of bodies applies to each other.
 * 
 *   0 1 2 3 4 5
 * 0   x x x x x
 * 1     x x x x
 * 2       x x x
 * 3         x x
 * 4           x
 * 5
 * 
 * Sum those forces together into an array of 3-vector x,y,z forces
 * 
 * Return 0 on success
 */

 // For all bodies:

  for (let i: i32 = 0; i < numBodies; i++) {                   // TypeScript.  i32 is type 32bit int
    // Given body i: pair with every body[j] where j > i
    for (let j: i32 = i + 1; j < numBodies; j++) {             // is this "n" or "log n"?
      // Calculate the force the bodies apply to one another
      stuff = stuff
    }
  }
  return stuff

我相當確定算法是 > O(n) 和 <= O(n*n)。

通過排除過程留下 O(n log n) 作為另一個選項。

看網格,我認為 O(1/2 n^2) = O(n^2)

查看循環,我認為內部循環是< n ,但我不確定它是否一直到log n

如果我通過 n 循環,添加log n內循環是什么樣的? 如果不是內循環,是外循環?

假設Calculate the force the bodies apply to one another是一個 O(1) 操作,那么你所擁有的是以下總和。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM