Algorithm 这是n体问题O(n^2)还是O(n log n)?
我正在写一篇关于n体问题的文章,我希望在技术上准确 代码是。下面是注释和循环:Algorithm 这是n体问题O(n^2)还是O(n log n)?,algorithm,big-o,complexity-theory,Algorithm,Big O,Complexity Theory,我正在写一篇关于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 b
/**
* 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
/**
*在3d空间中,给定N个具有质量的物体,计算要应用于每个物体的重力。
*
*此函数导出为JavaScript,因此只接受/返回数字和数组。
*对于N个物体,传递和排列4N个值(x,y,z,质量),并期望3N个力(x,y,z)排列
*这些力可应用于物体质量,以更新其在模拟中的位置。
*计算每个唯一实体对相互适用的3矢量。
*
* 0 1 2 3 4 5
*0 x x x
*1 x x x
*2 x x x
*3 x x
*4 x
* 5
*
*将这些力相加,形成一个3矢量x、y、z力的数组
*
*成功返回0
*/
//所有机构:
对于(设i:i32=0;ii
对于(让j:i32=i+1;j
我很确定算法是>O(n)和假设
计算物体相互作用的力是一个O(1)运算,那么你得到的是下面的总和
它是n+(n-1)+(n-2)+(n-3)+…1=(n*n)-(1+2+…+n)此算法具有二次时间复杂度,但它不是解决n体问题的最佳算法它是唯一具有机器精度的算法。