-- -- demo\rosetta\mmnn.exw -- -- Written in and distributed with Phix - see http://phix.x10.mx/ -- for https://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m#Phix -- with javascript_semantics include mpfr.e -- (for the final divide only) function mmnn(integer n) if n<=0 then return "0" end if -- (edge case) string digits = repeat(' ',n*(n+1)), res = "0" sequence parent = repeat(0,n*(n+1)), queue = {} integer dsum = 0, residue = 0, pdx = 0 while true do -- (found or queue not empty at end of loop) for digit=0 to 9 do if dsum>n then exit end if if dsum=n and residue=0 then -- success!! res[1] = '0'+digit while pdx do res = digits[pdx] & res pdx = parent[pdx] end while mpz z = mpz_init(res) assert(mpz_fdiv_q_ui(z, z, n)=0) res = mpz_get_str(z) return res end if integer drx = dsum*n+residue+1 if digits[drx]=' ' then digits[drx] = '0'+digit parent[drx] = pdx queue = append(queue,{dsum,residue}) end if dsum += 1 residue = remainder(residue+1,n) end for if length(queue)=0 then return "FAIL" end if {dsum,residue} = queue[1] queue = queue[2..$] pdx = dsum*n+residue+1 residue = remainder(residue*10,n) end while return "what???" end function for n=1 to 1000 do -- 2 mins 1s printf(1,"%d %s\n",{n,mmnn(n)}) // Generate b-file for A131382 end for