Greedy algorithm for Egyptian fractions: Difference between revisions

m
→‎{{header|Phix}}: bigatom -> mpfr
m (→‎{{header|Phix}}: bigatom -> mpfr)
Line 1,672:
=={{header|Phix}}==
{{trans|tcl}}
{{libheader|bigatommpfr}}
The sieve copied from Go
<lang Phix>include builtins\bigatommpfr.e
 
function egyptian(integer num, denom)
bigatommpz n = ba_newmpz_init(num),
d = ba_newmpz_init(denom),
t = mpz_init()
sequence result = {}
while mpz_cmp_si(n,0)!=BA_ZERO0 do
bigatom mpz_cdiv_q(t, = ba_ceil(ba_divide(d, n))
result = append(result,"1/"&mpz_get_str(t))
n = ba_modmpz_neg(ba_sub(BA_ZEROd,d),n)
d = ba_multiplympz_mod(n,d,tn)
mpz_neg(d,d)
mpz_mul(d,d,t)
end while
{n,d} = mpz_free({n,d})
return result
end function
Line 1,696 ⟶ 1,699:
prefix = sprintf("[%d] + ",whole)
end if
sequencestring se = join(egyptian(num, denom)," + ")
printf(1,"%d/%d -> %s%s\n",{num, denom, prefix & join(s," + ")e})
for i=1 to length(s) do s[i] = ba_sprintf("1/%B",s[i]) end for
printf(1,"%d/%d -> %s\n",{num, denom, prefix & join(s," + ")})
end procedure
Line 1,704 ⟶ 1,706:
efrac(5,121)
efrac(2014,59)
 
integer maxt = 0
string maxts = ""
integer maxd = 0
string maxds = ""
bigatom maxda
integer maxt = 0,
integer maxd = 0
string maxts = "",
string maxds = "",
maxda = ""
 
for r=98 to 998 by 900 do -- (iterates just twice!)
sequence sieve = repeat(repeat(false,r+1),r) -- to eliminate duplicates
Line 1,725 ⟶ 1,727:
maxts &= ", " & term
end if
integer mlen = length(ba_sprintf("%B",terms[$]))-2
if mlen>maxd then
maxd = mlen
Line 1,733 ⟶ 1,735:
maxds &= ", " & term
end if
if n < r/2 then
for k=2 to 9999 do
if d*k > r+1 then exit end if
Line 1,742 ⟶ 1,744:
end for
end for
printf(1,"\nfor proper fractions with 1 to %d digits\n",{length(sprint(r))})
printf(1,"for proper fractions with 1 to %d digits\n",{length(sprint(r))})
printf(1,"Largest number of terms is %d for %s\n",{maxt,maxts})
maxda = maxda[3..$] -- (strip the "1/")
string m_str = ba_sprintf("%B",maxda)
m_strmaxda[6..-6]="..." -- (show only first/last 5 digits)
printf(1,"Largest size for denominator is %d digits (%s) for %s\n",{maxd,m_strmaxda,maxds})
end for</lang>
{{out}}
7,818

edits