RGB is three dimensional, so to understand the problem it helps to visualise the RGB colour space as a three dimensional shape. A classic way is as a cube based on amounts of the three dimensions, red, green and blue:
(images taken from Digital Color Design with the RGB Color Cube: Visualization and Color Coordination Activities, a journal article I stumbled upon while writing this that's worth a read for anyone interested)
A cube with black and white at opposite corners, red green and blue at the corners next to black, and the mixes - yellow, cyan, magenta - at the corners connected to white. In the second example, 'up' adds green, 'down-left' adds red, 'down-right' adds blue.
How do you turn a cube into a flat plane? It's like turning a flat sheet of paper into a cube, but in reverse...
...you can do it by flattening the cube into a folding plan (like the top-right image) or by cutting slices out of the cube (like the top middle image). Then, you've got your colours, and how you arrange then is up to you.
But there's one thing missing - greys. All these colours are highly saturated. If you want to represent the whole of the RGB colour space, including greys and partially desaturated colours, you need to use a different set of three dimensions to generate your RGB cube: HSL (Hue, Saturation and Lightness) or HSB (Hue, Saturation and Brightness AKA HSV, Value).
This comparison (from wikimedia) shows cubes based on RGB, then HSL, then HSB:
(note that they're all RGB colours - HSL and HSB are just different ways of conceiving a colour space)
I'd suggest using something that loops through the RGB every possible HSB combination, spaced so that the number of results is just 40, then find a suitable way to arrange them, probably based on slices.
Be aware though that with 3 dimensions and just 40 figures, you won't have many steps. For example, you could have 2 levels of saturation (saturated, greyish), 3 levels of brightness (pale, medium, dark) and 6 levels of hue (blue, cyan, green, yellow, red, magenta), and that would give you 36 colours, leaving just 4 for the extremes (white, black, light grey, dark grey)