Integer roots: Difference between revisions

→‎{{header|Phix}}: bigatom -> mpfr
(→‎{{header|Phix}}: bigatom -> mpfr)
Line 665:
 
=={{header|Phix}}==
{{translibheader|Gompfr}}
<lang Phix>include bigatommpfr.e
function integer_root(integer n, object bA)
-- yields the nth root of A, adapted from https://en.wikipedia.org/wiki/Nth_root_algorithm
bigatom r = BA_ONE
bmpz res = ba_newmpz_init(b1),
x = mpz_init(),
delta = mpz_init()
A = mpz_init(A)
while true do
bigatom mpz_set(x = b,A)
for i=1 to mpz_pow_ui(delta,res,n-1 do)
mpz_fdiv_q(x, = ba_floor(ba_div(x,r) delta)
end formpz_sub(delta,x,res)
bigatom{} delta := ba_floormpz_fdiv_q_ui(ba_div(ba_sub(xdelta,r) delta, n))
if mpz_cmp_si(delta,0)=BA_ZERO0 then exit end if
r = ba_addmpz_add(rres,res,delta)
end while
return ba_sprintmpz_get_str(rres)
end function
printf(1,"3rd root of 8 = %s\n", {integer_root(3,8)})
printf(1,"3rd root of 9 = %s\n", {integer_root(3,9)})
string s = integer_root(2,"2e2002"&repeat('0',4000)) -- best I could manage...
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 cube root of 2: %s\n", {l,shorten(s)})</lang>
{{out}}
<pre>
3rd root of 8 = 2
3rd root of 9 = 2
First 101 digits of the square root of 2: 1414213562373095048 ...7107578486024636008 8503875343276415727(2001 digits)
First digits of the cube root of 2: 1259921049894873164...2546828353183047061 (2001 digits)
</pre>
 
7,794

edits