Integer roots: Difference between revisions

Content added Content deleted
(→‎{{header|Phix}}: bigatom -> mpfr)
Line 665: Line 665:


=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Go}}
{{libheader|mpfr}}
<lang Phix>include bigatom.e
<lang Phix>include mpfr.e
function integer_root(integer n, object b)
function integer_root(integer n, object A)
-- yields the nth root of A, adapted from https://en.wikipedia.org/wiki/Nth_root_algorithm
bigatom r = BA_ONE
b = ba_new(b)
mpz res = mpz_init(1),
x = mpz_init(),
delta = mpz_init()
A = mpz_init(A)
while true do
while true do
bigatom x = b
mpz_set(x,A)
for i=1 to n-1 do
mpz_pow_ui(delta,res,n-1)
x = ba_floor(ba_div(x,r))
mpz_fdiv_q(x, x, delta)
end for
mpz_sub(delta,x,res)
bigatom delta := ba_floor(ba_div(ba_sub(x,r),n))
{} = mpz_fdiv_q_ui(delta, delta, n)
if delta=BA_ZERO then exit end if
if mpz_cmp_si(delta,0)=0 then exit end if
r = ba_add(r,delta)
mpz_add(res,res,delta)
end while
end while
return ba_sprint(r)
return mpz_get_str(res)
end function
end function
printf(1,"3rd root of 8 = %s\n", {integer_root(3,8)})
printf(1,"3rd root of 8 = %s\n", {integer_root(3,8)})
printf(1,"3rd root of 9 = %s\n", {integer_root(3,9)})
printf(1,"3rd root of 9 = %s\n", {integer_root(3,9)})
string s = integer_root(2,"2e200") -- best I could manage...
string s = integer_root(2,"2"&repeat('0',4000))
printf(1,"First digits of the square root of 2: %s\n", {shorten(s)})
integer l = length(s)
s = integer_root(3,"2"&repeat('0',6000))
s[20..-20] = " ... "
printf(1,"First %d digits of the square root of 2: %s\n", {l,s})</lang>
printf(1,"First digits of the cube root of 2: %s\n", {shorten(s)})</lang>
{{out}}
{{out}}
<pre>
<pre>
3rd root of 8 = 2
3rd root of 8 = 2
3rd root of 9 = 2
3rd root of 9 = 2
First 101 digits of the square root of 2: 1414213562373095048 ... 8503875343276415727
First digits of the square root of 2: 1414213562373095048...7107578486024636008 (2001 digits)
First digits of the cube root of 2: 1259921049894873164...2546828353183047061 (2001 digits)
</pre>
</pre>