A problem arising in several engineering areas is to design magnets outside a volume that produce a desired magnetic field inside it. One instance of this problem is stellarator design, where it has recently been shown that permanent magnets can provide the required shaping of the magnetic field. Here we demonstrate a robust and efficient algorithm REGCOIL PM to calculate the spatial distribution of these permanent magnets. The procedure involves a small number of fixed-point iterations, with a linear least-squares problem solved at each step. The method exploits the Biot-Savart Law's exact linearity in magnetization density and approximate linearity in magnet size, for magnets far from the target region. No constraint is placed on the direction of magnetization, so Halbach solutions are found naturally, and the magnitude of the magnetization can be made uniformly equal to a target value.